<?php

namespace Home\Controller;

use Think\Cache\Driver\Redis;
use Think\Log;
use Think\Easemob;

class IndexController extends BaseMallController {

    function _empty($name) {
        echo '当前方法' . $name . '不存在';
    }

    /**
     * @api {get} /index.php?m=Home&c=Index&a=index 商城首页接口
     */
    function index() {
        //素材
        $data = array(
            'ads' => array(),
            'rec_store' => array(),
            'rec_goods' => array(),
        );
        $ads = M('app_ad')->order('sort_order desc')->select();
        foreach ($ads as $ad) {
            if (!$data['ads'][$ad['ad_type']]) {
                $data['ads'][$ad['ad_type']] = array();
            }
            $data['ads'][$ad['ad_type']][] = $ad;
        }

        //推荐店铺
        $rec_store = M('store')->where('recommended=1 AND state=1')->order('sort_order asc')->select();
        if ($rec_store) {
            $data['rec_store'] = $rec_store;
        }
        //推荐商品
         $rec_goods = M('goods')->alias('g')->join('__STORE__ s ON s.store_id=g.store_id')->field('g.*')->where('g.mall_recommended=1 AND g.if_show=1 AND g.closed=0 AND s.state=1')->order('mall_sort_order asc')->select();
        if ($rec_goods) {
            $data['rec_goods'] = $rec_goods;
        }
        render('10000', '', $data);
    }

    /**
     * @api {post} /index.php?m=Home&c=Index&a=login 登录相关接口
     * @apiName 登录相关接口
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 登录相关接口
     * 
     * @apiParam {String} user_name 用户名
     * @apiParam {String} password 密码
     * @apiParam {String} password 设备信息
     * 
     * @apiSuccess {String} user_id 日志ID
     * 
     */
    function login() {
        $user_info = array();
        $user_name = I('request.user_name');
        $password = I('request.password');
        $openid = I('request.openid'); //设备信息

        if ($user_name && $password) {
			
			$the_user=M('Member')->where('phone_mob="'.$user_name.'" OR user_name="'.$user_name.'" OR email="'.$user_name.'"')->field('user_name,user_id,s_name,s_id,u_name,portrait')->find();
			if($the_user){
				$user_name=$the_user['user_name'];
			}else{
				render('10106', '用户不存在',(object)array());
			}
			
            //验证账号密码
            $user_id = D("Member")->do_auth($user_name, $password);
            
            //登录赠送积分   积分部分重写
//            D('Integrallog')->change_integral_login($user_id);

            //执行登录操作后，更换一次token  此处先使用明文进行传输，后期使用加密算法进行验证。
            $token = md5('user_'.$user_id.'_'.'_'.time());
            //保存到app_token表
            M('AppToken')->add(array(
                'user_id' => $user_id,
                'token' => $token
            ));

            $store = M('store')->where(array('store_id'=>$the_user['s_id']))->find();

            $user_info['user_id'] = $user_id;
            $user_info['user_name'] = $user_name;
            $user_info['token'] = $token;
            $user_info['s_name'] = $the_user['s_name'];
            $user_info['store_logo'] = $store['store_logo'];
            $user_info['portrait'] = $the_user['portrait'] ? $the_user['portrait'] : '';
            $user_info['invite_code'] = set_encrypt($user_id);
            if ($openid) {
                //更新第三方登陆表
                $third_login = D("ThirdLogin")->get_info($openid);
                if (!$third_login) {
                    M("ThirdLogin")->add(array(
                        'third_name' => 'app',
                        'openid' => $openid,
                        'user_id' => $user_id,
                        'add_time' => time(),
                        'update_time' => time(),
                    ));
                } else {
                    M("ThirdLogin")->save(array(
                        'user_id' => $user_id,
                        'update_time' => time(),
                    ));
                }
            }
            $obj = new Easemob();
            if(!$the_user['u_name']){
                $rs = $obj->createUser('asa0'.$user_id,'asa0'.$user_id,'asa用户');
                if($rs['error'] == 'duplicate_unique_property_exists' || $rs['username']){
                    $res_uname = M('member')->where(array('user_id'=>$user_id))->save(array('u_name'=>'asa0'.$user_id));
                }
                $user_info['u_name'] = 'asa0'.$user_id;
            }else{
                $user_info['u_name'] = $the_user['u_name'];
            }
            $config_array = array(
                'app_key' => $obj->app_key,
                'customer_name' => $obj->customer_name,
                'tenant_id' => $obj->tenant_id,
                'project_id' => $obj->project_id,
            );
            render('10000', '登录成功', array(
                'user_info' => $user_info,
                'config' => $config_array
            ));
        } else {
            if (!$user_name) {
                render('10111', '用户名为空',(object)array());
            }
            if (!$password) {
                render('10112', '密码为空',(object)array());
            }
        }
    }

    /**
     * @api {get} /index.php?m=Home&c=Index&a=logout 退出相关接口
     * @apiName 退出相关接口
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 退出相关接口
     * 
     * @apiParam {String} user_name 用户名
     * @apiParam {String} password 密码
     * @apiParam {String} password 设备信息
     * 
     * @apiSuccess {String} user_id 日志ID
     */
    function logout() {
        if (!I('request.token')) {
            render('10001', '缺少参数');
        }
        M('AppToken')->where('token="' . I('request.token') . '"')->delete();
        render('10000', '退出成功');
    }

    /**
     * @api {get} /index.php?m=Home&c=Index&a=register 注册相关接口
     */
    function register() {

        // 把用户发送过来的request信息写入日志，Powered by liuzongyang 2019/10/8 18:12
        // 注册日志名称
        $logFile = C('LOG_PATH') . 'Register_' . date('y_m_d') . '.log';
        $message = '现在正在记录APP注册Request功能，请知悉： ' . PHP_EOL;
        $message .= '当前用户发送过来的Request信息如下: ' . PHP_EOL;
        // 把user-agent也放进去
        $_REQUEST['HTTP_USER_AGENT'] = $_SERVER['HTTP_USER_AGENT'];
        // 同时去掉用户的密码和确认密码字段，防止泄露，同时为了不影响下面的逻辑，复制一个临时变量代替
        $request_all = $_REQUEST;
        unset($request_all['password']);
        unset($request_all['password_confirm']);        
        $message .= print_r($request_all, true);
        Log::write($message, 'debug', '', $logFile);

        $user_info = array();
        $user_name = I('request.user_name', '');
        $phone_mob = I('request.phone_mob', '');
        //
        $openid = I('request.openid', '');
        $msg_sign = I('request.msg_sign', '');
        $msg_code = I('request.msg_code', '');
        $password = I('request.password', '');
        $city = I('request.city', '');
        $invite_code = I('request.invite_code', '');
//        $invite_code = set_encrypt('3|24');
        $password_confirm = I('request.password_confirm', '');
        if (!$phone_mob || !$msg_sign || !$msg_code || !$password_confirm || !$password) {
            render('10001', '缺少参数',(object)array());
        }
        if (md5('HomeIndexSet_password' . $msg_code) != $msg_sign) {
            render('10016', '短信验证码错误',(object)array());
        }
        if (!$user_name) {
            $user_name = $phone_mob;
        }
        $user_name_len = strlen($user_name);
        if ($user_name_len < 3 || $user_name_len > 25) {
            render('10103', '注册失败，用户名长度为3-25之间！',(object)array());
        }
        if ($password != $password_confirm) {
            /* 两次输入的密码不一致 */
            render('10102', '输入两次密码不一致！',(object)array());
        }
        $passlen = strlen($password);
        if ($passlen < 6 || $passlen > 20) {
            render('10104', '密码长度必须大于6位！',(object)array());
        }
        if($invite_code){
            $code = get_decrypt($invite_code);
            if(strstr($code, '|')){
                $temp_code = explode('|',$code);
                if(!$temp_code[0] || !$temp_code[1]){
                    render('10004','邀请码错误');
                }
                $res_1 = M('member')->where(array('user_id'=>$temp_code[0]))->find();
                $res_2 = M('wish')->where(array('id'=>$temp_code[1]))->find();
                if(!$res_1 || !$res_2){
                    render('10004','邀请码错误');
                }
                $cond_3 = array(
                    'id' => $temp_code[1],
                    'state' => 1
                );
                $referid = $res_2['user_id'];
                $refer_type = 2;
                $wish_id = $temp_code[1];
                $res_3 = M('wish')->where($cond_3)->find();
                if(!$res_3){
                    render('10004','心愿单已助力成功或者已过期');
                }
            }else{
                $res_1 = M('member')->where(array('user_id'=>$code))->find();
                if(!$res_1){
                    render('10004','邀请码错误');
                }
                $referid = $code;
                $refer_type = 1;
            }
            //判断是否为员工或者店铺分享
            if($res_1['first_class']){
                $first_class = $res_1['first_class'];
                //判断是否为二级店铺分享
                if($res_1['second_class']){
                    $second_class = $res_1['second_class'];
                    //判断是否为员工分享
                    if($res_1['third_class']){
                        $third_class = $res_1['third_class'];
                    }else{
                        $third_class = $res_1['user_id'];
                    }
                }else{
                    $second_class = 0;
                    $third_class = $res_1['user_id'];
                }

            }else{
                $res_mystore = M('store')->where(array('store_id'=>$res_1['user_id']))->find();
                if($res_mystore){
                	$s_id = $res_mystore['store_id'];
                	$s_name = $res_mystore['store_name'];
                }
            }
        }
        if($invite_code){
            $res_store = M('store')->where(array('store_id'=>$res_1['s_id']))->find();
        }else{
            if($city){
                $conds['region_name'] = array('like','%'.$city.'%');
                $res_city = M('region')->where($conds)->find();
                $county['region_id'] = $res_city['region_id'];
                $county['is_main'] = 0;
                $res_store = M('store')->where($county)->find();
                if(!$res_store){
                    $county['region_id'] = $res_city['parent_id'];
                    $county['is_main'] = 0;
                    $res_store = M('store')->where($county)->find();
                }
                if(!$res_store){
                    $cond['is_main'] = 1;
                    $res_store = M('store')->where($cond)->find();
                    if(!$res_store){
                        render('10104', '查找失败！',(object)array());
                    }
                }
            }else{
                $cond['is_main'] = 1;
                $res_store = M('store')->where($cond)->find();
                if(!$res_store){
                    render('10104', '查找失败！',(object)array());
                }
            }
        }
//        if($city){
//            //城市
//            if($invite_code){
//                $res_store = M('store')->where(array('store_id'=>$res_1['s_id']))->find();
//            }else{
//                $conds['region_name'] = array('like','%'.$city.'%');
//                $res_city = M('region')->where($conds)->find();
////        $county['region_id'] = array('IN',$res_city['region_id'].','.$res_city['parent_id']);
////        $county['is_main'] = 0;
//                $county['region_id'] = $res_city['region_id'];
//                $county['is_main'] = 0;
//                $res_store = M('store')->where($county)->find();
//                if(!$res_store){
//                    $county['region_id'] = $res_city['parent_id'];
//                    $county['is_main'] = 0;
//                    $res_store = M('store')->where($county)->find();
//                }
//                if(!$res_store){
//                    $cond['is_main'] = 1;
//                    $res_store = M('store')->where($cond)->find();
//                    if(!$res_store){
//                        render('10104', '查找失败！',(object)array());
//                    }
//                }
//            }
//
//        }else{
//            $cond['is_main'] = 1;
//            $res_store = M('store')->where($cond)->find();
//            if(!$res_store){
//                render('10104', '查找失败！',(object)array());
//            }
//        }

//        else{
//            $cond['is_main'] = 0;
//            $cond['parent_id'] = $res_county['region_id'];
//        }
//        $res_store = M('member')->where($cond)->find();
//        if(!$res_store){
//            render('10104', '查找失败！',(object)array());
//        }
//        $res_stores = M('store')->where(array('store_id'=>$res_store['s_id']))->find();
//        if(!$res_stores){
//            render('10104', '查找失败！',(object)array());
//        }
        $xcd['phone_mob'] = $phone_mob;
        $xcd['s_id'] = $s_id ? $s_id : $res_store['store_id'];
        $xcd['s_name'] =  $s_name ? $s_name : $res_store['store_name'];
        $xcd['referid'] =  $referid ? $referid : 0;
        $xcd['refer_type'] = $refer_type ? $refer_type : 0;
        $xcd['first_class'] = $first_class ? $first_class : 0;
        $xcd['second_class'] = $second_class ? $second_class : 0;
        $xcd['third_class'] = $third_class ? $third_class : 0;
        $user_id = D("Member")->do_register($user_name, $password, '', $xcd);
        if($refer_type == 2){
            $wish_controller = new \Home\Controller\WishController();
            $wish_controller->wish_log($referid,$user_id,$wish_id);
        }
        if ($user_id) {
            //登录赠送积分   积分部分重写
//            D('Integrallog')->change_integral_reg($user_id);
            $token = session_id();
            //保存到app_token表
            M('AppToken')->add(array(
                'user_id' => $user_id,
                'token' => $token
            ));
            $user_info['user_id'] = $user_id;
            $user_info['user_name'] = $phone_mob;
            $user_info['s_name'] = $res_store['store_name'];
            $user_info['store_logo'] = $res_store['store_logo'];
            $user_info['token'] = $token;
            $user_info['invite_code'] = set_encrypt($user_id);

            if($invite_code){
                $code = get_decrypt($invite_code);
                $temp_code = explode('|',$code);
            }
            if ($openid) {
                //记录登录设备信息
                $third_login = D("ThirdLogin")->get_info($openid);
                if (!$third_login) {
                    M("ThirdLogin")->add(array(
                        'third_name' => 'app',
                        'openid' => $openid,
                        'user_id' => $user_id,
                        'add_time' => time(),
                        'update_time' => time(),
                    ));
                } else {
                    M("ThirdLogin")->save(array(
                        'user_id' => $user_id,
                        'update_time' => time(),
                    ));
                }
            }

            // 把response响应信息写入日志，Powered by liuzongyang 2019/10/8 18:15
            $message = '现在正在记录APP注册的Response功能，请知悉： ' . PHP_EOL;
            $message .= '待发送给用户的Response信息如下: ' . PHP_EOL;
            $message .= print_r($user_info, true);
            Log::write($message, 'debug', '', $logFile);

            // 把日志也保存到数据库
            // 其中最终返回数据input保存在一个Register数组中
            $params = [
                'method' => $_SERVER['REQUEST_METHOD'],
                'ip' => real_ip(),
                'path' => $_SERVER['QUERY_STRING'],
                'admin_id' => $user_id,
                'admin_name' => $phone_mob,
                // 默认中文不转码                
                'input' => json_encode([
                    'Register' => [
                        'Request' => $request_all,
                        'Response' => $user_info,
                    ]
                ], JSON_UNESCAPED_UNICODE),
            ];
            $log = &M('admin_log');
            $log->add($params);
            $obj = new Easemob();
            $the_user = M('member')->where(array('user_id'=>$user_id))->find();
            $user_info['portrait'] = $the_user['portrait'] ? $the_user['portrait'] : '';
            if(!$the_user['u_name']){
                $rs = $obj->createUser('asa0'.$user_id,'asa0'.$user_id,'asa用户');
                if($rs['error'] == 'duplicate_unique_property_exists' || $rs['username']){
                    $res_uname = M('member')->where(array('user_id'=>$user_id))->save(array('u_name'=>'asa0'.$user_id));
                }
                $user_info['u_name'] = 'asa0'.$user_id;
            }else{
                $user_info['u_name'] = $the_user['u_name'];
            }
            $config_array = array(
                'app_key' => $obj->app_key,
                'customer_name' => $obj->customer_name,
                'tenant_id' => $obj->tenant_id,
                'project_id' => $obj->project_id,
            );
            render('10000', '注册成功', array(
                'user_info' => $user_info,
                'config' => $config_array
            ));

        }
    }

    /**
     * @api {post} /index.php?m=Home&c=Index&a=set_password 设置登录密码
     * 
     */
    function set_password() {
        $password = I('request.password', '');
        $password_confirm = I('request.password_confirm', '');
        $user_id = I('request.user_id', '');
        $msg_sign = I('request.msg_sign', '');
        $msg_code = I('request.msg_code', '');
        if (!$user_id || !$password_confirm || !$password) {
            render('10001', '缺少参数');
        }
        if ($msg_sign) {
            if (md5('HomeIndexSet_password' . $msg_code) != $msg_sign) {
                render('10016', '短信验证码错误');
            }
        }
        $member = M('Member')->where('user_id=' . $user_id)->find();
        $available = array();
        if ($member['password']) {
            if (!$msg_sign) {
                render('10116', '用户已设置登录密码');
            }
        } else {
            $available = array('available' => 0);
        }
        if (!$member) {
            render('10106', '用户不存在');
        }


        if ($password != $password_confirm) {
            /* 两次输入的密码不一致 */
            render('10102', '输入两次密码不一致！');
        }
        $passlen = strlen($password);
        if ($passlen < 6 || $passlen > 20) {
            render('10104', '密码长度必须大于6位！');
        }

        M('Member')->where('user_id=' . $user_id)->save(array_merge(array('password' => md5($password)), $available));
        render('10000', '设置密码成功');
    }

    /**
     * @api {get} /index.php?m=Home&c=Index&a=find_password 找回密码接口
     * 
     */
    function find_password() {
        $user_name = I('request.user_name');
        if (!$user_name) {
            render('10111', '用户名为空');
        }
        $member = M('Member')->where('user_name="' . $user_name . '" OR phone_mob="' . $user_name . '"')->find();
        if (!$member) {
            render('10106', '用户不存在');
        }
        if (!$member['phone_mob']) {
            render('10117', '用户未设置手机号');
        }
        $to_mobile = $member['phone_mob'];
        D('Msglog')->send_msg_system('find', $to_mobile);
        $msg_sign = md5('HomeIndexSet_password' . $_SESSION['MobileConfirmCode']);
        render('10000', '短信发送成功!', array('user_id' => $member['user_id'], 'msg_sign' => $msg_sign));
    }

    /**
     * @api {get} /index.php?m=Home&c=Index&a=send_messages 发送短信接口
     * 
     */
    function send_messages() {
        $to_mobile = I('request.mobile');
        if (!$to_mobile) {
            render('10012', '手机号码为空');
        }
        D('Msglog')->send_msg_system('register', $to_mobile);
        $msg_sign = md5('HomeIndexSet_password' . $_SESSION['MobileConfirmCode']);
        render('10000', '短信发送成功!', array('msg_sign' => $msg_sign));
    }

//    lichen 2019/6/5 start
    /**
     * @api {get} /index.php?m=Home&c=Index&a=revise_password 修改密码
     *
     */
    function revise_password() {
        $user_name = I('request.user_name');
        if (!$user_name) {
            render('10111', '用户名为空');
        }
        $member = M('Member')->where('user_name="' . $user_name . '" OR email="' . $user_name . '" OR phone_mob="' . $user_name . '"')->find();
        if (!$member) {
            render('10106', '用户不存在');
        }
        if (!$member['phone_mob']) {
            render('10117', '用户未设置手机号');
        }
        $to_mobile = $member['phone_mob'];
        D('Msglog')->send_msg_system('change', $to_mobile);
        $msg_sign = md5('HomeIndexSet_password' . $_SESSION['MobileConfirmCode']);
        render('10000', '短信发送成功!', array('user_id' => $member['user_id'], 'msg_sign' => $msg_sign));
    }
//    lichen 2019/6/5 end
    /**
     * @api {get} /index.php?m=Home&c=Index&a=scategory 获取所有店铺分类
     * 
     */
    function scategory() {
        $scategories = D("Scategory")->get_list();
        import("Org.Com.Tree");
        $tree = new \Org\Com\Tree;
        $tree->setTree($scategories, 'cate_id', 'parent_id', 'cate_name');
        $data = $tree->getArrayList(0);
        foreach ($data as $key1 => $val1) {
            if (!empty($val1['children'])) {
                foreach ($val1['children'] as $key2 => $val2) {
                    if (empty($val2['children'])) {
                        $data[$key1]['children'][$key2]['no_children'] = true;
                    }
                }
            } else {
                $data[$key1]['no_children'] = true;
            }
        }
        render('10000', 'OK', array('category' => $data));
    }

    /**
     * @api {get} /index.php?m=Home&c=Index&a=gcategory 获取所有商品分类
     * 
     */
    function gcategory() {
        $gcategories = D("Gcategory")->get_list();
        import("Org.Com.Tree");
        $tree = new \Org\Com\Tree;
        $tree->setTree($gcategories, 'cate_id', 'parent_id', 'cate_name');
        $data = $tree->getArrayList(0);
//        lichen 2019/5/30 start
        $res = M('banner_setting')->where(array('type_id'=>3))->select();
        $datar['banner'] = $res;
        $resr = M('person_setting')->order('sort_order')->select();
        $resf = M('limited_setting')->find();
        $datar['all'] = array(
            'cate_logo' => $resf['sort_url']
        );
        $datar['person'] = $resr;
        $datar['catef'] = array();
        $datar['catel'] = array();
        $res_parents1 = M('gcategory')->where(array('parent_id'=>0,'if_show'=>1))->order('sort_order asc')->select();
        $data_id = array();
        foreach ($res_parents1 as $k => $v){
            $data_id[] = $v['cate_id'];
        }
        $cond['parent_id'] = array('in',$data_id);
        $res_parents2 = M('gcategory')->where($cond)->limit(9)->order('sort_order asc')->select();
        $datar['catef'] = $res_parents1 ? $res_parents1 : (object)array();
        $datar['catel'] = $res_parents2 ? $res_parents2 : (object)array();
//        lichen 2019/5/30 end
//        foreach ($data as $key1 => $val1) {
////                lichen 2019/5/30 start
//            $data[$key1]['cate_logo'] = $gcategories[$val1['id']]['cate_logo'];
//            $datar['catef'][] = $data[$key1];
////                lichen 2019/5/30 end
//            if (!empty($val1['children'])) {
//                foreach ($val1['children'] as $key2 => $val2) {
//                    $data[$key1]['children'][$key2]['cate_logo'] = $gcategories[$val2['id']]['cate_logo'];
//                    if (!empty($val2['children'])) {
////                lichen 2019/5/30 start
////                lichen 2019/5/30 end
//                        foreach ($val2['children'] as $key3 => $val3) {
//                            $data[$key1]['children'][$key2]['children'][$key3]['cate_logo'] = $gcategories[$val3['id']]['cate_logo'];
//                            $datar['catel'][] = $data[$key1]['children'][$key2]['children'][$key3];
//                        }
//                    } else {
//                        $data[$key1]['children'][$key2]['no_children'] = true;
//                        $datar['catel'][] = $data[$key1]['children'][$key2];
//                    }
//                }
//            } else {
//                $data[$key1]['no_children'] = true;
//                $datar['catel'][] = $data[$key1];
//            }
//        }
//        lichen 2019/5/30 start
        render('10000', 'OK', $datar);
//        render('10000', 'OK', array('category' => $data));
//        lichen 2019/5/30 end
    }

    /**
     * @api {get} /index.php?m=Home&c=Index&a=region_list 获得地区列表
     * 
     */
    function region_list() {
        $region_list = M('region')->select();
        import("Org.Com.Tree");
        $tree = new \Org\Com\Tree;
        $tree->setTree($region_list, 'region_id', 'parent_id', 'region_name');
        $data = $tree->getArrayList(0);
        foreach ($data as $key1 => $val1) {
            if (!empty($val1['children'])) {
                foreach ($val1['children'] as $key2 => $val2) {
                    if (empty($val2['children'])) {
                        $data[$key1]['children'][$key2]['no_children'] = true;
                    }
                }
            } else {
                $data[$key1]['no_children'] = true;
            }
        }
        render('10000', 'OK', array('region_list' => $data));
    }

    /**
     * @api {get} /index.php?m=Home&c=Index&a=recommend_goods 获得推荐产品列表
     * @apiName 获得推荐产品列表
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 获得推荐产品列表
     * 
     * @apiSuccess {String} goods_id 商品ID
     * @apiSuccess {String} goods_name 商品名称
     * @apiSuccess {String} default_image 默认图片
     * @apiSuccess {String} price 价格
     * @apiSuccess {String} market_price 市场价格
     * 
     */
    function recommend_goods() {
        $map['if_show'] = 1;
        $map['closed'] = 0;
        $map['mall_recommended'] = 1;
        $goods_list = M('goods')->field('goods_id,goods_name,default_image,price,market_price')
                ->where($map)
                ->order('mall_sort_order desc')
                ->select();
        render('10000', 'OK', array('goods_list' => $goods_list));
    }

    /**
     * @api {get} /index.php?m=Home&c=Index&a=recommend_store 获得推荐店铺列表
     * @apiName 获得推荐店铺列表
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 获得推荐店铺列表
     * 
     * @apiSuccess {String} store_id 店铺ID
     * @apiSuccess {String} store_name 店铺名称
     * @apiSuccess {String} store_logo 店铺LOGO
     * 
     */
    function recommend_store() {
        $map['state'] = 1;
        $map['recommended'] = 1;
        $store_list = M('goods')->field('store_id,store_name,store_logo')
                ->where($map)
                ->order('sort_order desc')
                ->select();
        render('10000', 'OK', array('store_list' => $store_list));
    }

    /**
     * @api {get} /index.php?m=Home&c=Index&a=promotion_list 获得促销产品列表
     * @apiName 获得促销产品列表
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 获得促销产品列表
     * 
     * @apiSuccess {String} pro_id 促销ID
     * @apiSuccess {String} goods_id 商品ID
     * @apiSuccess {String} pro_name 促销名称
     * @apiSuccess {String} start_time 开始时间
     * @apiSuccess {String} end_time 结束时间
     * @apiSuccess {String} pro_recommended 促销推荐
     * @apiSuccess {String} default_image 促销图片
     * @apiSuccess {String} price 正常价格
     * @apiSuccess {String} pro_price 促销价格
     * @apiSuccess {String} goods_name 商品名称
     * 
     */
    function promotion_list() {
        $time = time();
        $map['start_time'] = array('lt', $time);
        $map['end_time'] = array('gt', $time);
        $promotion_list = M('promotion')->field('pro.*,g.default_image,g.price,g.default_spec,g.goods_name,g.default_spec')
                ->alias('pro')
                ->join('LEFT JOIN ' . C('DB_PREFIX') . 'goods g ON g.goods_id = pro.goods_id')
                ->where($map)
                ->page(I('request.page', 1, 'intval') . ',10')
                ->select();
        if ($promotion_list) {
            foreach ($promotion_list as $key => $goods) {
                $pro_price = D('Promotion')->get_promotion_price($goods['goods_id'], $goods['default_spec']);
                if ($pro_price < $goods['price']) {
                    $promotion_list[$key]['pro_price'] = $pro_price;
                } else {
                    $promotion_list[$key]['pro_price'] = $goods['price'];
                }
            }
        }
        render('10000', '', array('promotion_list' => $promotion_list));
    }

    /**
     * @api {get} /index.php?m=Home&c=Index&a=search_goods 搜索相关产品
     */
     function search_goods() {
        $conditions = 'g.if_show=1 AND g.closed=0 AND s.state=1';
        $keyword = I('request.keyword', '');
        if ($keyword) {
            $conditions .= ' AND goods_name LIKE "%'.$keyword.'%"' ;
        }
        
        $cate_id = I('request.cate_id', '0', 'intval');
        if ($cate_id) {
            $conditions .= ' AND (cate_id_1=' . $cate_id . ' OR cate_id_2=' . $cate_id . ' OR cate_id_3=' . $cate_id . ' OR cate_id_4=' . $cate_id.')';
        }
        
        //排序
        $sort = I('request.sort', '');
        $order = I('request.order', '');
        if (!in_array($sort, array('sales', 'price', 'add_time', 'comments'))) {
            $sort = 'sales';
        }
        if (!in_array($order, array('desc', 'asc'))) {
            $order = 'desc';
        }
        $goods_mod = M('goods');
        $goods_list = $goods_mod
                ->where($conditions)
                ->field('g.goods_id,g.store_id,g.goods_name,g.default_image,g.price,gs.sales,gs.comments,g.add_time')->alias('g')
                ->join('LEFT JOIN ' . C('DB_PREFIX') . 'store s ON s.store_id = g.store_id')
                ->join('LEFT JOIN ' . C('DB_PREFIX') . 'goods_statistics gs ON gs.goods_id = g.goods_id')
                ->page(I('request.page', 1, 'intval') . ',10')
                ->order($sort . ' ' . $order)
                ->select();
        /*
        if ($goods_list) {
            foreach ($goods_list as $key => $goods) {
                $goods_list[$key]['price'] = D('Promotion')->get_promotion_price($goods['goods_id'], $goods['spec_id']);
            }
        }
         */
        $data = array(
            'goods_list' => $goods_list,
        );
        render('10000', 'OK', $data);
    }

    /**
     * @api {get} /index.php?m=Home&c=Index&a=search_store 搜索相关店铺
     * 
     */
    function search_store() {
        $map = array('state' => 1);
        $keyword = I('request.keyword', '');
        if ($keyword) {
            $map['store_name'] = array('LIKE', '%' . $keyword . '%');
        }

        $cate_id = I('request.cate_id', '0', 'intval');
        if ($cate_id) {
            $cate_ids = D('Scategory')->get_descendant($cate_id);
            $map['cate_id'] = array('IN', implode(',', $cate_ids));
        }

        //排序
        $sort = I('request.sort', '');
        $order = I('request.order', '');
        if (!in_array($sort, array('sales', 'credit_value', 'add_time', 'praise_rate'))) {
            $sort = 'sales';
        }
        if (!in_array($order, array('desc', 'asc'))) {
            $order = 'desc';
        }


        $store_mod = M('store');
        $subQuery = M('Store')->alias('store')->field('COUNT(*) as sales,store.store_id')->join('LEFT JOIN ' . C('DB_PREFIX') . 'order order_alias ON store.store_id = order_alias.seller_id')->group('store_id')->buildSql();
        $store_list = $store_mod->field('store.store_id,store.store_name,store.store_logo')
                ->alias('store')
                ->where($map)
                ->join('LEFT JOIN ' . $subQuery . ' a ON a.store_id=store.store_id')
                ->join('LEFT JOIN ' . C('DB_PREFIX') . 'category_store category_store ON store.store_id = category_store.store_id')
                ->order($sort . ' ' . $order)
                ->page(I('request.page', 1, 'intval') . ',10')
                ->select();
        foreach ($store_list as $key => $val) {
            $store_list[$key]['goods_list'] = M('Goods')->field('goods_id,goods_name,default_image,price')->where('store_id=' . $val['store_id'] . ' AND if_show=1 AND closed=0')->order('add_time desc')->limit(12)->select();
            $store_list[$key]['total_count'] = M('Goods')->where('store_id=' . $val['store_id'] . ' AND if_show=1 AND closed=0')->count();
        }
        $data = array(
            'store_list' => $store_list,
        );
        render('10000', 'OK', $data);
    }

    function homepage(){
        if(!$_POST['page'] || !$_POST['pagenum']){
            render('10001', '参数错误');
        }
        if($_POST['page'] == 1){
            $resBanner = M('banner_setting')->where(array('type_id' => 1))->order('sort_order')->limit(5)->select();
            $data['banner'] = $resBanner;
            $resSort = M('sort_setting')->where()->order('sort_order')->limit(3)->select();
            $data['sort'] = $resSort;
        }

        $resTheme = M('theme_setting')->where(array('preview'=>1))->order('sort_order')->limit($_POST['pagenum'])->page($_POST['page'])->select();
        $data['theme'] = $resTheme;
//        if($_POST['page'] % 2 == 1){
        $resRecommend = M('recommend_setting')->where()->order('sort_order')->limit(1)->page($_POST['page']/2+1)->find();
        if($resRecommend['goods_id']){
            $cond['goods_id'] = array('in',$resRecommend['goods_id']);
            $res = M('goods')->where($cond)->select();
            $resRecommend['goods'] = $res;
            $condCount['is_show'] = 1;
            $condCount['closed'] = 0;
            $condCount['add_time'] = array('between',array(time()-7*86400,time()));
            $resRecommend['recommend_count'] = M('goods')->where($condCount)->count();
        }else{
            $resRecommend = json_decode('{}');
        }
        $resLimited = M('limitedtime_setting')->find();
        $data['limited'] = $resLimited ? $resLimited : (object)array();
        $data['hot_search'] = explode(',',C('HOT_SEARCH'));
        $data['search_keywords'] = C('SEARCH_KEYWORDS');
        render('10000', 'OK', $data);
    }

    function get_homepage(){
        if(!$_POST['page'] || !$_POST['pagenum']){
            render('10001', '参数错误');
        }
        if($_POST['page'] == 1){
            $resBanner = M('banner_setting')->where(array('type_id' => 1,'preview'=>1))->order('sort_order')->limit(5)->select();
            $data['banner'] = $resBanner;
            $resSort = M('sort_setting')->where()->order('sort_order')->limit(3)->select();
            $data['sort'] = $resSort;
        }

        $resTheme = M('theme_setting')->where(array('theme_time'=>array('ELT',time()),'preview'=>1))->order('sort_order')->limit($_POST['pagenum'])->page($_POST['page'])->select();
        //商品外挂
        foreach ($resTheme as $key => $value){
            $conditions = ' AND g.if_show=1 AND g.closed=0 AND s.state=1';
            $conditions .= ' AND g.goods_id IN('.$value['goods_id'].')';
            $conditions1 = $conditions;
            $conditions1 .= ' AND tg.theme_id ='.$value['theme_id'];

            $list = M('goods')
                ->table('ecm_goods g,ecm_goods_spec gsp,ecm_storestock ss,ecm_store s,ecm_goods_statistics gs,ecm_theme_goods tg')
                ->field('g.brand,g.goods_id,g.store_id,g.goods_name,g.default_image,g.price,g.times,g.market_price,gs.comments,g.add_time,group_concat(gsp.stock) as stocks,group_concat(gsp.spec_2) as spec_2s,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist, MAX(case when gsp.stock=0 or gsp.price=0.00 or gsp.discount_price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.discount_price end) as end_discount_price, MIN(case when gsp.stock=0 or gsp.price=0.00 or gsp.discount_price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.discount_price end) as first_discount_price,MAX(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.price end) as end_cost_price,MIN(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.price end) as first_cost_price,ifnull(g.label ,"") as label,convert(MIN(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.price end) * 10/g.market_price,decimal(10,1)) as discount,tg.sort_order,tg.theme_id,ifnull(SUBSTRING(g.times,1,2 ),"") as ftimes,ifnull(SUBSTRING(g.times,3 ),"") as ltimes')
                ->where('g.goods_id = gsp.goods_id and gsp.spec_3value = ss.storestock_id and s.store_id = g.store_id and gs.goods_id = g.goods_id and g.goods_id = tg.goods_id '.$conditions1)
                ->limit(10)
                ->group('g.goods_id')
                ->having('is_exist = "true"')
//            ->order('is_exist desc,'.$sort . ' ' . $order.',mall_sort_order asc')
                ->order('tg.sort_order ASC,ifnull(SUBSTRING(g.times,3 ),"") DESC,ifnull(SUBSTRING(g.times,1,2 ),"") ASC')
                ->buildSql();
            $goods_list = M('discount')->alias('d')
                ->field("cc.store_id as sto_id,ifnull(cc.ico ,'') as ico,gl.*")
                ->join('right join '.$list.' gl on d.goods_id = gl.goods_id')
                ->join('left join ecm_coupon_codes cc on d.coupon_codes_id = cc.id and cc.enabled = 1')
                ->group('gl.goods_id')
//            ->order($sort . ' ' . $order)
                ->order('gl.sort_order ASC,ifnull(SUBSTRING(gl.times,3 ),"") DESC,ifnull(SUBSTRING(gl.times,1,2 ),"") ASC')
//            ->where(array('cc.enabled'=>1))
                ->select();
            if($_POST['token']){
                $res_token = M('app_token')->where(array('token'=>$_POST['token']))->find();
                $res_user = M('member')->where(array('user_id'=>$res_token['user_id']))->find();
            }
            foreach ($goods_list as $k => $v) {
                if ($v['sto_id'] && $_POST['token'] && $res_user){
                    $res_store_goods = M('store')->where(array('store_id'=>$v['sto_id']))->find();
                    $res_store_user = M('store')->where(array('store_id'=>$res_user['s_id']))->find();
                    $res_region_goods = M('region')->where(array('region_id'=>$res_store_goods['region_id']))->find();
                    $res_region_user = M('region')->where(array('region_id'=>$res_store_user['region_id']))->find();
                    if($res_region_user['region_id'] == $res_region_goods['region_id'] || $res_region_user['parent_id'] == $res_region_goods['region_id'] || $res_region_user['region_id'] == $res_region_goods['parent_id']){
                        //显示优惠价
                        $goods_list[$k]['first_price'] = ($v['first_discount_price'] < $v['first_cost_price']) && $v['first_discount_price'] ? $v['first_discount_price'] : $v['first_cost_price'];
//                    $goods_list[$k]['end_price'] = ($v['end_discount_price'] < $v['end_cost_price']) && $v['end_discount_price'] ? $v['end_discount_price'] : $v['end_cost_price'];
                        $goods_list[$k]['end_price'] = $goods_list[$k]['first_price'];
                    }else{
                        //显示普通价
                        $goods_list[$k]['first_price'] = $v['first_cost_price'];
//                    $goods_list[$k]['end_price'] = $v['end_cost_price'];
                        $goods_list[$k]['end_price'] = $goods_list[$k]['first_price'];
                        $goods_list[$k]['ico'] = '';
                    }
                }else if(strlen($v['sto_id']) && $v['sto_id'] == '0'){
                    //显示优惠价
                    $goods_list[$k]['first_price'] = ($v['first_discount_price'] < $v['first_cost_price']) && $v['first_discount_price'] ? $v['first_discount_price'] : $v['first_cost_price'];
//                $goods_list[$k]['end_price'] = ($v['end_discount_price'] < $v['end_cost_price']) && $v['end_discount_price'] ? $v['end_discount_price'] : $v['end_cost_price'];
                    $goods_list[$k]['end_price'] = $goods_list[$k]['first_price'];
                }else{
                    //显示普通价
                    $goods_list[$k]['first_price'] = $v['first_cost_price'];
//                $goods_list[$k]['end_price'] = $v['end_cost_price'];
                    $goods_list[$k]['end_price'] = $goods_list[$k]['first_price'];
                    $goods_list[$k]['ico'] = '';
                }
            }
                //临时
            $resTheme[$key]['goods'] = $goods_list;
//            $resTheme[$key]['goods'] = array();
            $counts = M('goods')
                ->table('ecm_goods g,ecm_goods_spec gsp,ecm_storestock ss,ecm_store s,ecm_goods_statistics gs')
                ->field('g.brand,g.goods_id,g.goods_name,g.mall_sort_order,g.add_time,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist, MAX(case when gsp.stock=0 or gsp.price=0.00 or gsp.discount_price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.discount_price end) as end_discount_price, MIN(case when gsp.stock=0 or gsp.price=0.00 or gsp.discount_price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.discount_price end) as first_discount_price,MAX(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.price end) as end_cost_price,MIN(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.price end) as first_cost_price')
                ->where('g.goods_id = gsp.goods_id and gsp.spec_3value = ss.storestock_id and s.store_id = g.store_id and gs.goods_id = g.goods_id   '.$conditions)
                ->group('g.goods_id')
                ->having('is_exist = "true"')
//            ->order('is_exist desc,'.$sort . ' ' . $order.',mall_sort_order asc')
                ->order('g.mall_sort_order asc,g.add_time desc')
                ->select();
            $resTheme[$key]['counts'] = count($counts) ? count($counts) : 0;

        }
        $data['theme'] = $resTheme;


//        if($_POST['page'] % 2 == 1){
        $resRecommend = M('recommend_setting')->where()->order('sort_order')->limit(1)->page($_POST['page']/2+1)->find();
        if($resRecommend['goods_id']){
            $cond['goods_id'] = array('in',$resRecommend['goods_id']);
            $cond['if_show'] = 1;
            $cond['closed'] = 0;
            $res = M('goods')->where($cond)->select();
            $resRecommend['goods'] = $res;
            $condCount['if_show'] = 1;
            $condCount['closed'] = 0;
            $condCount['add_time'] = array('between',array(time()-7*86400,time()));
            $resRecommend['recommend_count'] = M('goods')->where($condCount)->count();
        }else{
            $resRecommend = json_decode('{}');
        }
//        $resLimited = M('limited_setting')->find();
        //redis
        $redis = connectRedis();
        //zRevRangeByScore 分数排行
        //专题
        if($redis ->zRevRangeByScore('hot_theme','+inf','-inf') && count($redis ->zRevRangeByScore('hot_theme','+inf','-inf') > 1)){
            $res_hot_theme = $redis ->zRevRangeByScore('hot_theme','+inf','-inf',array('withscores' => FALSE, 'limit' => array(0,2)));
        }else{
            $res_hot_theme = M('hot_theme')->order('sort_order asc')->limit(2)->getfield('theme_title',true);
        }
        //改为发货方式
        $data['hot_theme'] = $res_hot_theme;
        $data['stock_name'] = array('境内仓','香港直邮仓');
        //品牌
//        $redis->zDelete('hot_brand','VERSACE');
        if($redis ->zRevRangeByScore('hot_brand','+inf','-inf') && count($redis ->zRevRangeByScore('hot_brand','+inf','-inf') > 7)){
            $res_hot_brand = $redis ->zRevRangeByScore('hot_brand','+inf','-inf',array('withscores' => FALSE, 'limit' => array(0,8)));
        }else{
            $res_hot_brand = M('hot_brand')->order('sort_order asc')->limit(8)->getfield('brand_name',true);
        }
        $data['hot_brand'] = $res_hot_brand;
        //关键词
        if($redis ->zRevRangeByScore('hot_keyword','+inf','-inf') && count($redis ->zRevRangeByScore('hot_keyword','+inf','-inf') > 0)){
            $res_hot_keyword = $redis ->zRevRangeByScore('hot_keyword','+inf','-inf',array('withscores' => FALSE, 'limit' => array(0,1)));
        }else{
            $res_hot_keyword = array('上衣');
        }
        $data['hot_keyword'] = $res_hot_keyword[0];
        //var_dump($redis ->zRevRangeByScore('hot_theme','+inf','-inf'));

        render('10000', 'OK', $data);


    }

    /**
     * 递归查出所有分类
     */
    function getTree($data,$cate_id){
        $tree = array();
        foreach($data as $k => $v) {

            if($v['parent_id'] == $cate_id)
            {
                $v['newArr'] = $this->getTree($data, $v['cate_id']);
                if(is_array($v['newArr']) && !empty($v['newArr'])){
                    foreach($v['newArr'] as $key=>$value){
                        $tree[]['cate_id'] = $value['cate_id'];
                    }
                }
                $tree[]['cate_id'] = $v['cate_id'];
            }
        }
        return $tree;
    }

    /**
     * 查询分类的方法
     * lixinguo
     */
    function get_cateList($cate_id)
    {

        //todo 获取当前分类ID是否为父级分类
        $cateModel = D("gcategory");
        $cateInfo = $cateModel->select();
        $treeList = $this->getTree($cateInfo,$cate_id);
        //todo 当前分类是父级分类
        //todo 获取当前父级分类下的所有子分类
        $arr = array();
        if(!empty($treeList)){
            $ids = '';
            foreach($treeList as $k=>$v){
                $ids .= $v['cate_id'] .',';
            }
            //todo 当前分类ID是父级
            $arr['parent_id'] = 9999;
            $arr['ids'] = $ids .$cate_id;
        }else{
            //todo 当前分类ID不是父级
            $arr['parent_id'] = 1111;
            $arr['ids'] = $cate_id;
        }
        return $arr;

    }

//    lichen 2019/5/30 start

    function get_list(){
        $conditions = ' AND g.if_show=1 AND g.closed=0 AND s.state=1';
        $keyword = I('request.keyword', '');
        $kw = explode(' ',$keyword);
        $kw = array_filter($kw);
        sort($kw);
        if($_POST['sex']){
            $arr = explode(',',$_POST['sex']);
            foreach ($arr as $key=>$value){
                $arr[$key] = '"'. $arr[$key] . '"';
            }
            $str = implode(',',$arr);
            $conditions .= ' AND g.sex IN('.$str.')';
        }
        if($_POST['brands']){
            $arr = explode(',',$_POST['brands']);
            foreach ($arr as $key=>$value){
                $arr[$key] = '"'. $arr[$key] . '"';
            }
            $str = implode(',',$arr);
            $conditions .= ' AND g.brand IN('.$str.')';
        }
        if($_POST['cate_names']){
            $temp_cate = explode(',',$_POST['cate_names']);
            foreach ($temp_cate as $k => $v){
                if($k == 0 && $k == count($temp_cate) - 1){
                    $conditions .= ' AND (g.cate_name LIKE "%'.$v.'%")';
                }else if($k == 0){
                    $conditions .= ' AND (g.cate_name LIKE "%'.$v.'%"';
                }else if($k == count($temp_cate) - 1){
                    $conditions .= ' OR g.cate_name LIKE "%'.$v.'%")';
                }else{
                    $conditions .= ' OR g.cate_name LIKE "%'.$v.'%"';
                }
            }
        }
        if($_POST['price']){
            $tn_arr = explode('-',$_POST['price']);
            if(!$tn_arr[1]){
                $conditions .= ' AND gsp.price>='.$tn_arr[0];
            }else{
                $conditions .= ' AND gsp.price>='.$tn_arr[0].' AND gsp.price<='.$tn_arr[1];
            }
        }
        if($_POST['spec_2']){
            $arr = explode(',',$_POST['spec_2']);
            foreach ($arr as $key=>$value){
                $arr[$key] = '"'. $arr[$key] . '"';
            }
            $str = implode(',',$arr);
            $conditions .= ' AND gsp.spec_2 IN('.$str.')';
        }
        if($_POST['spec_1value']){
            $arr = explode(',',$_POST['spec_1value']);
            foreach ($arr as $key=>$value){
                $arr[$key] = '"'. $arr[$key] . '"';
            }
            $str = implode(',',$arr);
            $conditions .= ' AND gsp.spec_1value IN('.$str.')';
        }
        if($_POST['stock_name']){
            $arr = explode(',',$_POST['stock_name']);
            foreach ($arr as $key=>$value){
                $arr[$key] = '"'. $arr[$key] . '"';
            }
            $str = implode(',',$arr);
            $conditions .= ' AND ss.stock_name IN('.$str.')';
        }
        if ($keyword) {
            //redis
            set_redis('hot_keyword',$keyword);
            foreach ($kw as $key => $value){
                //先查男女
                if($key == 0 && $key == count($kw) - 1){
                    $conditions .= ' AND (goods_name LIKE "%'.$value.'%" OR brand LIKE "%'.$value.'%" OR cate_name LIKE "%'.$value.'%" OR sex LIKE "%'.$value.'%" OR gsp.spec_1value LIKE "%'.$value.'%" OR gsp.spec_1 LIKE "%'.$value.'%" OR gsp.spec_3 LIKE "%'.$value.'%")';
                }else if($key == 0){
                    $conditions .= ' AND (goods_name LIKE "%'.$value.'%" OR brand LIKE "%'.$value.'%" OR cate_name LIKE "%'.$value.'%" OR sex LIKE "%'.$value.'%" OR gsp.spec_1value LIKE "%'.$value.'%" OR gsp.spec_1 LIKE "%'.$value.'%" OR gsp.spec_3 LIKE "%'.$value.'%"';
                }else if($key == count($kw) - 1){
                    $conditions .= ' OR goods_name LIKE "%'.$value.'%" OR brand LIKE "%'.$value.'%" OR cate_name LIKE "%'.$value.'%" OR sex LIKE "%'.$value.'%" OR gsp.spec_1value LIKE "%'.$value.'%" OR gsp.spec_1 LIKE "%'.$value.'%" OR gsp.spec_3 LIKE "%'.$value.'%")';
                }else{
                    $conditions .= ' OR goods_name LIKE "%'.$value.'%" OR brand LIKE "%'.$value.'%" OR cate_name LIKE "%'.$value.'%" OR sex LIKE "%'.$value.'%" OR gsp.spec_1value LIKE "%'.$value.'%" OR gsp.spec_1 LIKE "%'.$value.'%" OR gsp.spec_3 LIKE "%'.$value.'%"';
                }
            }
        }
        $brand = htmlspecialchars_decode(I('request.brand', ''));
        if ($brand) {
            $conditions .= ' AND brand = "'.$brand.'"';
            //redis
            set_redis('hot_brand',$brand);
            //zRevRangeByScore 分数排行
            //var_dump($redis ->zRevRangeByScore('hot_theme','+inf','-inf'));
            //
        }

        $cate_id = I('request.cate_id', '0', 'intval');
        if ($cate_id) {
//            $conditions .= ' AND (cate_id_1=' . $cate_id . ' OR cate_id_2=' . $cate_id . ' OR cate_id_3=' . $cate_id . ' OR cate_id_4=' . $cate_id.')';

            //todo 调取分类查询
            $result = $this->get_cateList($cate_id);
            if($result['parent_id'] == 9999){
                $conditions .= ' AND cate_id IN ('.$result['ids'].')';
            }else{
                $conditions .= ' AND cate_id='.$result['ids'];
            }
        }
        $cate = I('request.cate', '');
        if ($cate) {
            $conditions .= ' AND cate_name LIKE "%'.$cate.'%"';
        }

        //排序
        $sort = I('request.sort', '');
        $order = I('request.order', '');
        $sign = ',';
        if (!in_array($sort, array('sales', 'price', 'add_time', 'comments','discount'))) {
            $sort = '';
            $sign = '';
        }
        if (!in_array($order, array('desc', 'asc'))) {
            $order = '';
        }
        //goods_id
        $goods_id = I('request.goods_id', '');
        if(trim($goods_id)){
            $conditions .= ' AND g.goods_id IN ('.$goods_id.')';
        }
        //banner_id
        $banner_id= I('request.banner_id', '');
        if(trim($banner_id)){
            $res_banner = M('banner_goods')->where(array('banner_id'=>$banner_id))->select();
            if($res_banner){
                $res_temp_array = array_column($res_banner,'goods_id');
                $res_temp_str = implode(',',$res_temp_array);
                $conditions .= ' AND g.goods_id IN ('.$res_temp_str.')';
            }
        }


//        $goods_mod = M('goods');
        //新版本 不要已售罄商品

//        $goods_list = M('goods')
//            ->table('ecm_goods g,ecm_goods_spec gsp,ecm_storestock ss,ecm_store s,ecm_goods_statistics gs')
//            ->field('g.brand,g.goods_id,g.store_id,g.goods_name,g.default_image,g.price,g.market_price,gs.sales,gs.comments,g.add_time,gs.goods_id,group_concat(gsp.stock) as stocks,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 as is_exist')
//            ->where('g.goods_id = gsp.goods_id and gsp.spec_3value = ss.storestock_id and s.store_id = g.store_id and gs.goods_id = g.goods_id'.$conditions)
//            ->page(I('request.page', 1, 'intval') . ',10')
//            ->group('g.goods_id')
//            ->order($sort . ' ' . $order.',mall_sort_order asc')
//            ->select();
        if($sort == 'price'){
            $sort = 'first_cost_price';
        }
        $conditions1 = $conditions;
        if(trim($banner_id)){
            $conditions1 .= ' AND bg.banner_id ='.$banner_id;
        }
        if($banner_id){
            $list = M('goods')
                ->table('ecm_goods g,ecm_goods_spec gsp,ecm_storestock ss,ecm_store s,ecm_goods_statistics gs,ecm_banner_goods bg')
                ->field('g.brand,g.goods_id,g.store_id,g.goods_name,g.default_image,g.price,g.times,g.market_price,gs.comments,g.add_time,group_concat(gsp.stock) as stocks,group_concat(gsp.spec_2) as spec_2s,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist, MAX(case when gsp.stock=0 or gsp.price=0.00 or gsp.discount_price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.discount_price end) as end_discount_price, MIN(case when gsp.stock=0 or gsp.price=0.00 or gsp.discount_price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.discount_price end) as first_discount_price,MAX(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.price end) as end_cost_price,MIN(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.price end) as first_cost_price,ifnull(g.label ,"") as label,convert(MIN(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.price end) * 10/g.market_price,decimal(10,1)) as discount,bg.sort_order,bg.banner_id,ifnull(SUBSTRING(g.times,1,2 ),"") as ftimes,ifnull(SUBSTRING(g.times,3 ),"") as ltimes')
                ->where('g.goods_id = gsp.goods_id and gsp.spec_3value = ss.storestock_id and s.store_id = g.store_id and gs.goods_id = g.goods_id and g.goods_id = bg.goods_id '.$conditions1)
                ->page(I('request.page', 1, 'intval') . ',10')
                ->group('g.goods_id')
                ->having('is_exist = "true"')
//            ->order('is_exist desc,'.$sort . ' ' . $order.',mall_sort_order asc')
                ->order($sort . ' ' . $order.$sign.'bg.sort_order ASC,ifnull(SUBSTRING(g.times,3 ),"") DESC,ifnull(SUBSTRING(g.times,1,2 ),"") ASC')
                ->buildSql();
            $goods_list = M('discount')->alias('d')
                ->field("cc.store_id as sto_id,ifnull(cc.ico ,'') as ico,gl.*")
                ->join('right join '.$list.' gl on d.goods_id = gl.goods_id')
                ->join('left join ecm_coupon_codes cc on d.coupon_codes_id = cc.id and cc.enabled = 1')
                ->group('gl.goods_id')
//            ->order($sort . ' ' . $order)
                ->order($sort . ' ' . $order.$sign.'gl.sort_order ASC,ifnull(SUBSTRING(gl.times,3 ),"") DESC,ifnull(SUBSTRING(gl.times,1,2 ),"") ASC')
//            ->where(array('cc.enabled'=>1))
                ->select();
        }else{
            $list = M('goods')
                ->table('ecm_goods g,ecm_goods_spec gsp,ecm_storestock ss,ecm_store s,ecm_goods_statistics gs')
                ->field('g.brand,g.goods_id,g.store_id,g.goods_name,g.default_image,g.price,g.times,g.market_price,gs.comments,g.add_time,group_concat(gsp.stock) as stocks,group_concat(gsp.spec_2) as spec_2s,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist, MAX(case when gsp.stock=0 or gsp.price=0.00 or gsp.discount_price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.discount_price end) as end_discount_price, MIN(case when gsp.stock=0 or gsp.price=0.00 or gsp.discount_price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.discount_price end) as first_discount_price,MAX(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.price end) as end_cost_price,MIN(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.price end) as first_cost_price,ifnull(g.label ,"") as label,convert(MIN(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.price end) * 10/g.market_price,decimal(10,1)) as discount,ifnull(SUBSTRING(g.times,1,2 ),"") as ftimes,ifnull(SUBSTRING(g.times,3 ),"") as ltimes')
                ->where('g.goods_id = gsp.goods_id and gsp.spec_3value = ss.storestock_id and s.store_id = g.store_id and gs.goods_id = g.goods_id '.$conditions)
                ->page(I('request.page', 1, 'intval') . ',10')
                ->group('g.goods_id')
                ->having('is_exist = "true"')
//            ->order('is_exist desc,'.$sort . ' ' . $order.',mall_sort_order asc')
                ->order($sort . ' ' . $order.$sign.'ifnull(SUBSTRING(g.times,3 ),"") DESC,ifnull(SUBSTRING(g.times,1,2 ),"") ASC')
                ->buildSql();
            $goods_list = M('discount')->alias('d')
                ->field("cc.store_id as sto_id,ifnull(cc.ico ,'') as ico,gl.*")
                ->join('right join '.$list.' gl on d.goods_id = gl.goods_id')
                ->join('left join ecm_coupon_codes cc on d.coupon_codes_id = cc.id and cc.enabled = 1')
                ->group('gl.goods_id')
//            ->order($sort . ' ' . $order)
                ->order($sort . ' ' . $order.$sign.'ifnull(SUBSTRING(gl.times,3 ),"") DESC,ifnull(SUBSTRING(gl.times,1,2 ),"") ASC')
//            ->where(array('cc.enabled'=>1))
                ->select();
        }

        if($_POST['token']){
            $res_token = M('app_token')->where(array('token'=>$_POST['token']))->find();
            $res_user = M('member')->where(array('user_id'=>$res_token['user_id']))->find();
        }

        foreach ($goods_list as $k => $v) {
            //年代
            if($v['times']) {
                $temp_times = substr($v['times'],2,strlen($v['times'])-1);
                $goods_list[$k]['times_label'] = (int)$temp_times <= 2015 ? '过季特卖': '';
            }else{
                $goods_list[$k]['times_label'] = '';
            }
            //折扣
            if($v['discount']) {
                if ($v['discount'] > 3.5 && $v['discount'] < 6){
                    $goods_list[$k]['discount_label'] = '折扣';
                }else if($v['discount'] < 3.5 && $v['discount'] > 0){
                    $goods_list[$k]['discount_label'] = '清仓';
                }else{
                    $goods_list[$k]['discount_label'] = '';
                }
            }else{
                $goods_list[$k]['discount_label'] = '';
            }
            //
            if($v['label'] == '正常'){
                $goods_list[$k]['label'] = '';
            }
            //按尺码分组
            $list_a = M('goods')
                ->table('ecm_goods g,ecm_goods_spec gsp,ecm_storestock ss,ecm_store s,ecm_goods_statistics gs')
                ->field('gsp.spec_2,group_concat(gsp.stock) as stocks,group_concat(gsp.spec_2) as spec_2s,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist')
                ->where('g.goods_id = gsp.goods_id and gsp.spec_3value = ss.storestock_id and s.store_id = g.store_id and gs.goods_id = g.goods_id and g.goods_id='.$v['goods_id'])
                ->group('gsp.spec_2')
                ->having('is_exist = "true"')
//            ->order('is_exist desc,'.$sort . ' ' . $order.',mall_sort_order asc')
                ->select();
            $arr = array_column($list_a,'spec_2');
            //尺码排序
            //1.先把数字排前面
            $arr_num = $arr ? $this->array_number_second($arr) : array();
            sort($arr_num);
            //2.按照尺码表取数字
            $arr_str = M('size_order')->group('size_name')->order('size_order asc')->select();
            $arr_str ? $arra_str = array_column($arr_str,'size_name') : array();
            //按顺序取出
            $arrs = $this->array_sort_second($arra_str,$arr);
            //数组合并
            $goods_list[$k]['spec_2s'] = array_merge($arr_num,$arrs);
            //按发货地分组
            $list_b = M('goods')
                ->table('ecm_goods g,ecm_goods_spec gsp,ecm_storestock ss,ecm_store s,ecm_goods_statistics gs')
                ->field('gsp.spec_2,ss.stock_name,group_concat(gsp.stock) as stocks,group_concat(gsp.spec_2) as spec_2s,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist')
                ->where('g.goods_id = gsp.goods_id and gsp.spec_3value = ss.storestock_id and s.store_id = g.store_id and gs.goods_id = g.goods_id and g.goods_id='.$v['goods_id'])
                ->group('ss.storestock_id')
                ->having('is_exist = "true"')
//            ->order('is_exist desc,'.$sort . ' ' . $order.',mall_sort_order asc')
                ->select();

            //发货地排序
            $array_unset = $this->array_unset_second($list_b,'stock_name');
            $arr = array_column($array_unset,'stock_name');
            $arrv = $this->array_sort_second(array( 0 => '境内仓',
                1 => '天津保税仓',
                2 => '香港直邮仓',
                3 => '海外直邮仓'),$arr);
            $goods_list[$k]['stock_names'] = $arrv;

            if ($v['sto_id'] && $_POST['token'] && $res_user){
                $res_store_goods = M('store')->where(array('store_id'=>$v['sto_id']))->find();
                $res_store_user = M('store')->where(array('store_id'=>$res_user['s_id']))->find();
                $res_region_goods = M('region')->where(array('region_id'=>$res_store_goods['region_id']))->find();
                $res_region_user = M('region')->where(array('region_id'=>$res_store_user['region_id']))->find();
                if($res_region_user['region_id'] == $res_region_goods['region_id'] || $res_region_user['parent_id'] == $res_region_goods['region_id'] || $res_region_user['region_id'] == $res_region_goods['parent_id']){
                    //显示优惠价
                    $goods_list[$k]['first_price'] = ($v['first_discount_price'] < $v['first_cost_price']) && $v['first_discount_price'] ? $v['first_discount_price'] : $v['first_cost_price'];
//                    $goods_list[$k]['end_price'] = ($v['end_discount_price'] < $v['end_cost_price']) && $v['end_discount_price'] ? $v['end_discount_price'] : $v['end_cost_price'];
                    $goods_list[$k]['end_price'] = $goods_list[$k]['first_price'];
                }else{
                    //显示普通价
                    $goods_list[$k]['first_price'] = $v['first_cost_price'];
//                    $goods_list[$k]['end_price'] = $v['end_cost_price'];
                    $goods_list[$k]['end_price'] = $goods_list[$k]['first_price'];
                    $goods_list[$k]['ico'] = '';
                }
            }else if(strlen($v['sto_id']) && $v['sto_id'] == '0'){
                //显示优惠价
                $goods_list[$k]['first_price'] = ($v['first_discount_price'] < $v['first_cost_price']) && $v['first_discount_price'] ? $v['first_discount_price'] : $v['first_cost_price'];
//                $goods_list[$k]['end_price'] = ($v['end_discount_price'] < $v['end_cost_price']) && $v['end_discount_price'] ? $v['end_discount_price'] : $v['end_cost_price'];
                $goods_list[$k]['end_price'] = $goods_list[$k]['first_price'];
            }else{
                //显示普通价
                $goods_list[$k]['first_price'] = $v['first_cost_price'];
//                $goods_list[$k]['end_price'] = $v['end_cost_price'];
                $goods_list[$k]['end_price'] = $goods_list[$k]['first_price'];
                $goods_list[$k]['ico'] = '';
            }
        }
        //总筛选
        $res_sort = M('goods')
            ->table('ecm_goods g,ecm_store s,ecm_goods_spec gsp,ecm_storestock as ss')
            ->field('g.cate_name,substring_index(g.cate_name," ",1) as parent_name,count(substring_index(g.cate_name," ",1)) as num,group_concat(gsp.stock) as stocks,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist,g.sex,g.brand,gsp.spec_1value,gsp.spec_2,g.material,ss.stock_name')
            ->where('g.store_id = s.store_id AND g.goods_id = gsp.goods_id AND gsp.spec_3value = ss.storestock_id'.$conditions)
            ->group('g.goods_id')
            ->order('count(substring_index(g.cate_name," ",1)) desc')
            ->having('is_exist = "true"')
            ->select();

        //筛选 按尺码
        $res_sort_spec_2 = M('goods')
            ->table('ecm_goods g,ecm_store s,ecm_goods_spec gsp,ecm_storestock as ss')
            ->field('g.cate_name,substring_index(g.cate_name," ",1) as parent_name,count(substring_index(g.cate_name," ",1)) as num,group_concat(gsp.stock) as stocks,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist,g.sex,g.brand,gsp.spec_1value,gsp.spec_2,g.material,ss.stock_name')
            ->where('g.store_id = s.store_id AND g.goods_id = gsp.goods_id AND gsp.spec_3value = ss.storestock_id'.$conditions)
            ->group('gsp.spec_2')
            ->having('is_exist = "true"')
            ->select();
        //筛选 按颜色
        $res_sort_spec_1value = M('goods')
            ->table('ecm_goods g,ecm_store s,ecm_goods_spec gsp,ecm_storestock as ss')
            ->field('g.cate_name,substring_index(g.cate_name," ",1) as parent_name,count(substring_index(g.cate_name," ",1)) as num,group_concat(gsp.stock) as stocks,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist,g.sex,g.brand,gsp.spec_1value,gsp.spec_2,g.material,ss.stock_name')
            ->where('g.store_id = s.store_id AND g.goods_id = gsp.goods_id AND gsp.spec_3value = ss.storestock_id'.$conditions)
            ->group('gsp.spec_1value')
            ->having('is_exist = "true"')
            ->select();
        //筛选 按仓库
        $res_sort_stock_name = M('goods')
            ->table('ecm_goods g,ecm_store s,ecm_goods_spec gsp,ecm_storestock as ss')
            ->field('g.cate_name,substring_index(g.cate_name," ",1) as parent_name,count(substring_index(g.cate_name," ",1)) as num,group_concat(gsp.stock) as stocks,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist,g.sex,g.brand,gsp.spec_1value,gsp.spec_2,g.material,ss.stock_name')
            ->where('g.store_id = s.store_id AND g.goods_id = gsp.goods_id AND gsp.spec_3value = ss.storestock_id'.$conditions)
            ->group('ss.stock_name')
//            ->order('count(substring_index(g.cate_name," ",1)) desc')
            ->having('is_exist = "true"')
            ->select();

        //二级筛选
        $array_second = array();
        //性别
        //text 名称 value 值 key 返回字段 type 类型(0,1,2) num 数量 is_single 是否复选(true,false) choose 最多可选
        $array_unset= $this->array_unset_second($res_sort,'sex');
        $arr = array_column($array_unset,'sex');
        $arrv = $this->array_sort_second(array('女','男','儿童','中性'),$arr);
        $array_second [] = array(
            'text' => '性别',
            'value' => $arrv,
            'key' => 'sex',
            'type' => 0,
            'num' => 0,
            'is_single' => false,
            'choose' => '4'
        );
        //品牌
        $array_unset = $this->array_unset_second($res_sort,'brand');
        $arr = array_column($array_unset,'brand');
        sort($arr);
        $arrs = $this->array_sort_second(array('HERMES', 'GUCCI', 'BURBERRY', 'OFF WHITE', 'KENZO', 'VALENTINO', 'CANADA GOOSE', 'MSGM', 'BALENCIAGA'),$arr);
        $arrss = $this->array_unset_sort_second($arrs,$arr);
        $arrv = $arrs ? array_merge($arrs,$arrss) : $arrss;
        $array_second [] = array(
            'text' => '品牌',
            'value' => $arrv,
            'key' => 'brands',
            'type' => 1,
            'num' => 9,
            'is_single' => false,
            'choose' => '5'
        );
        //分类
        $array_unset = $this->array_unset_second($res_sort,'parent_name');
        $arr = array_column($array_unset,'parent_name');
        $array_second [] = array(
            'text' => '分类',
            'value' => $arr,
            'key' => 'cate_names',
            'type' => 1,
            'num' => 9,
            'is_single' => false,
            'choose' => '5'
        );
        //价格
        $array_second [] = array(
            'text' => '价格',
            'value' => array('0-1000','1000-2000','2000-4000','4000-8000','8000-15000','15000-0'),
            'key' => 'price',
            'type' => 2,
            'num' => 0,
            'is_single' => true,
            'choose' => '1'
        );
        //尺码
        $array_unset = $this->array_unset_second($res_sort_spec_2,'spec_2');
        $arr = array_column($array_unset,'spec_2');
        //尺码排序
        //1.先把数字排前面
        $arr ? $arr_num = $this->array_number_second($arr) : array();
        sort($arr_num);
        //2.按照尺码表取数字
        $arr_str = M('size_order')->order('mode_id asc,size_order asc')->group('size_name')->select();
        $arr_str ? $arra_str = array_column($arr_str,'size_name') : array();
        //按顺序取出
        $arrs = $this->array_sort_second($arra_str,$arr);
        //数组合并
        $arrv = array_merge($arr_num,$arrs);
        //
        $array_second [] = array(
            'text' => '尺码',
            'value' => $arrv,
            'key' => 'spec_2',
            'type' => 1,
            'num' => 9,
            'is_single' => false,
            'choose' => '5'
        );
        //颜色
        $array_unset = $this->array_unset_second($res_sort_spec_1value,'spec_1value');
        $arr = array_column($array_unset,'spec_1value');
        $array_second [] = array(
            'text' => '颜色',
            'value' => $arr,
            'key' => 'spec_1value',
            'type' => 1,
            'num' => 0,
            'is_single' => false,
            'choose' => '5'
        );
        //材质 暂时取消
//        $array_unset = $this->array_unset_second($res_sort,'material');
//        $arr = array_column($array_unset,'material');
//        $array_second [] = array(
//            'k' => array('材质'),
//            'v' => $arr,
//            'c' => array('material'),
//        );
        //发货地
        $array_unset = $this->array_unset_second($res_sort_stock_name,'stock_name');
        $arr = array_column($array_unset,'stock_name');
        $arrv = $this->array_sort_second(array( 0 => '境内仓',
            1 => '天津保税仓',
            2 => '香港直邮仓',
            3 => '海外直邮仓'),$arr);
        $array_second [] = array(
            'text' => '发货地',
            'value' => $arrv,
            'key' => 'stock_name',
            'type' => 1,
            'num' => 0,
            'is_single' => false,
            'choose' => '4'
        );
        //排序
        //关闭exist
//        if (!in_array( I('request.sort'), array('sales', 'price', 'add_time', 'comments')) && !in_array(I('request.order'), array('desc', 'asc'))) {
//            $last_names = array_column($goods_list,'is_exist');
//            array_multisort($last_names,SORT_DESC,$goods_list);
//        }
//        $_POST['user_id'] = 3;
        if($_POST['user_id']){
            $cond_collect['user_id'] = $_POST['user_id'];
            $res_collect = M('collect')->where($cond_collect)->field('item_id as goods_id ,user_id')->select();
            foreach ($goods_list as $key => $value){
                $res_spec = M('goods_spec')->group('spec_1value')->where(array('goods_id'=>$value['goods_id']))->field('spec_1')->select();
                $data = array_column($res_spec,'spec_1');
                $goods_list[$key]['spec'] = $data;
                if($res_collect){
                    if(in_array($goods_list[$key]['goods_id'],array_column($res_collect,'goods_id'))){
                        $goods_list[$key]['collect'] = true;
                    }else{
                        $goods_list[$key]['collect'] = false;
                    }
//                    if($goods_list[$key]['goods_id'] == 21){
//                        var_dump($goods_list[$key]['collect']);exit;
//                    }
                }else{
                    $goods_list[$key]['collect'] = false;
                }
            }
        }else{
            foreach ($goods_list as $key => $value){
                $res_spec = M('goods_spec')->group('spec_1value')->where(array('goods_id'=>$value['goods_id']))->field('spec_1')->select();
                $data = array_column($res_spec,'spec_1');
                $goods_list[$key]['spec'] = $data;
            }
        }
        /*
        if ($goods_list) {
            foreach ($goods_list as $key => $goods) {
                $goods_list[$key]['price'] = D('Promotion')->get_promotion_price($goods['goods_id'], $goods['spec_id']);
            }
        }
         */
        if(!$goods_list){
            $goods_list = array();
        }
        $res = M('banner_setting')->where(array('type_id'=>2))->select();
        $data = array(
            'goods_list' => $goods_list,
            'banner' => $res,
            'cate' => array(),
            'second' => $array_second
        );
        render('10000', 'OK', $data);
    }

    function get_banner(){
        $conditions = ' AND g.if_show=1 AND g.closed=0 AND s.state=1';
        $keyword = I('request.keyword', '');
        $kw = explode(' ',$keyword);
        $kw = array_filter($kw);
        sort($kw);
        if($_POST['sex']){
            $arr = explode(',',$_POST['sex']);
            foreach ($arr as $key=>$value){
                $arr[$key] = '"'. $arr[$key] . '"';
            }
            $str = implode(',',$arr);
            $conditions .= ' AND g.sex IN('.$str.')';
        }
        if($_POST['brands']){
            $arr = explode(',',$_POST['brands']);
            foreach ($arr as $key=>$value){
                $arr[$key] = '"'. $arr[$key] . '"';
            }
            $str = implode(',',$arr);
            $conditions .= ' AND g.brand IN('.$str.')';
        }
        if($_POST['cate_names']){
            $temp_cate = explode(',',$_POST['cate_names']);
            foreach ($temp_cate as $k => $v){
                if($k == 0 && $k == count($temp_cate) - 1){
                    $conditions .= ' AND (g.cate_name LIKE "%'.$v.'%")';
                }else if($k == 0){
                    $conditions .= ' AND (g.cate_name LIKE "%'.$v.'%"';
                }else if($k == count($temp_cate) - 1){
                    $conditions .= ' OR g.cate_name LIKE "%'.$v.'%")';
                }else{
                    $conditions .= ' OR g.cate_name LIKE "%'.$v.'%"';
                }
            }
        }
        if($_POST['price']){
            $tn_arr = explode('-',$_POST['price']);
            if(!$tn_arr[1]){
                $conditions .= ' AND gsp.price>='.$tn_arr[0];
            }else{
                $conditions .= ' AND gsp.price>='.$tn_arr[0].' AND gsp.price<='.$tn_arr[1];
            }
        }
        if($_POST['spec_2']){
            $arr = explode(',',$_POST['spec_2']);
            foreach ($arr as $key=>$value){
                $arr[$key] = '"'. $arr[$key] . '"';
            }
            $str = implode(',',$arr);
            $conditions .= ' AND gsp.spec_2 IN('.$str.')';
        }
        if($_POST['spec_1value']){
            $arr = explode(',',$_POST['spec_1value']);
            foreach ($arr as $key=>$value){
                $arr[$key] = '"'. $arr[$key] . '"';
            }
            $str = implode(',',$arr);
            $conditions .= ' AND gsp.spec_1value IN('.$str.')';
        }
        if($_POST['stock_name']){
            $arr = explode(',',$_POST['stock_name']);
            foreach ($arr as $key=>$value){
                $arr[$key] = '"'. $arr[$key] . '"';
            }
            $str = implode(',',$arr);
            $conditions .= ' AND ss.stock_name IN('.$str.')';
        }
        if ($keyword) {
            //redis
            set_redis('hot_keyword',$keyword);
            foreach ($kw as $key => $value){
                //先查男女
                if($key == 0 && $key == count($kw) - 1){
                    $conditions .= ' AND (goods_name LIKE "%'.$value.'%" OR brand LIKE "%'.$value.'%" OR cate_name LIKE "%'.$value.'%" OR sex LIKE "%'.$value.'%" OR gsp.spec_1value LIKE "%'.$value.'%" OR gsp.spec_1 LIKE "%'.$value.'%" OR gsp.spec_3 LIKE "%'.$value.'%")';
                }else if($key == 0){
                    $conditions .= ' AND (goods_name LIKE "%'.$value.'%" OR brand LIKE "%'.$value.'%" OR cate_name LIKE "%'.$value.'%" OR sex LIKE "%'.$value.'%" OR gsp.spec_1value LIKE "%'.$value.'%" OR gsp.spec_1 LIKE "%'.$value.'%" OR gsp.spec_3 LIKE "%'.$value.'%"';
                }else if($key == count($kw) - 1){
                    $conditions .= ' OR goods_name LIKE "%'.$value.'%" OR brand LIKE "%'.$value.'%" OR cate_name LIKE "%'.$value.'%" OR sex LIKE "%'.$value.'%" OR gsp.spec_1value LIKE "%'.$value.'%" OR gsp.spec_1 LIKE "%'.$value.'%" OR gsp.spec_3 LIKE "%'.$value.'%")';
                }else{
                    $conditions .= ' OR goods_name LIKE "%'.$value.'%" OR brand LIKE "%'.$value.'%" OR cate_name LIKE "%'.$value.'%" OR sex LIKE "%'.$value.'%" OR gsp.spec_1value LIKE "%'.$value.'%" OR gsp.spec_1 LIKE "%'.$value.'%" OR gsp.spec_3 LIKE "%'.$value.'%"';
                }
            }
        }
        $brand = htmlspecialchars_decode(I('request.brand', ''));
        if ($brand) {
            $conditions .= ' AND brand = "'.$brand.'"';
            //redis
            set_redis('hot_brand',$brand);
            //zRevRangeByScore 分数排行
            //var_dump($redis ->zRevRangeByScore('hot_theme','+inf','-inf'));
            //
        }

        $cate_id = I('request.cate_id', '0', 'intval');
        if ($cate_id) {
//            $conditions .= ' AND (cate_id_1=' . $cate_id . ' OR cate_id_2=' . $cate_id . ' OR cate_id_3=' . $cate_id . ' OR cate_id_4=' . $cate_id.')';

            //todo 调取分类查询
            $result = $this->get_cateList($cate_id);
            if($result['parent_id'] == 9999){
                $conditions .= ' AND cate_id IN ('.$result['ids'].')';
            }else{
                $conditions .= ' AND cate_id='.$result['ids'];
            }
        }
        $cate = I('request.cate', '');
        if ($cate) {
            $conditions .= ' AND cate_name LIKE "%'.$cate.'%"';
        }

        //排序
        $sort = I('request.sort', '');
        $order = I('request.order', '');
        $sign = ',';
        if (!in_array($sort, array('sales', 'price', 'add_time', 'comments','discount'))) {
            $sort = '';
            $sign = '';
        }
        if (!in_array($order, array('desc', 'asc'))) {
            $order = '';
        }
        //goods_id
        $goods_id = I('request.goods_id', '');
        if(trim($goods_id)){
            $conditions .= ' AND g.goods_id IN ('.$goods_id.')';
        }
        //banner_id
        $banner_id= I('request.banner_id', '');
        if(trim($banner_id)){
            $res_banner = M('banner_goods')->field('group_concat(goods_id) as sgoods_id')->where(array('banner_id'=>$banner_id))->group('banner_id')->find();
            if($res_banner){
                $conditions .= ' AND g.goods_id IN ('.$res_banner['sgoods_id'].')';
            }
        }


        $goods_mod = M('goods');
        //新版本 不要已售罄商品

//        $goods_list = M('goods')
//            ->table('ecm_goods g,ecm_goods_spec gsp,ecm_storestock ss,ecm_store s,ecm_goods_statistics gs')
//            ->field('g.brand,g.goods_id,g.store_id,g.goods_name,g.default_image,g.price,g.market_price,gs.sales,gs.comments,g.add_time,gs.goods_id,group_concat(gsp.stock) as stocks,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 as is_exist')
//            ->where('g.goods_id = gsp.goods_id and gsp.spec_3value = ss.storestock_id and s.store_id = g.store_id and gs.goods_id = g.goods_id'.$conditions)
//            ->page(I('request.page', 1, 'intval') . ',10')
//            ->group('g.goods_id')
//            ->order($sort . ' ' . $order.',mall_sort_order asc')
//            ->select();
        if($sort == 'price'){
            $sort = 'first_cost_price';
        }
        $list = M('goods')
            ->table('ecm_goods g,ecm_goods_spec gsp,ecm_storestock ss,ecm_store s,ecm_goods_statistics gs,ecm_banner_goods bg')
            ->field('g.brand,g.goods_id,g.store_id,g.goods_name,g.default_image,g.price,g.times,g.market_price,gs.comments,g.add_time,group_concat(gsp.stock) as stocks,group_concat(gsp.spec_2) as spec_2s,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist, MAX(case when gsp.stock=0 or gsp.price=0.00 or gsp.discount_price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.discount_price end) as end_discount_price, MIN(case when gsp.stock=0 or gsp.price=0.00 or gsp.discount_price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.discount_price end) as first_discount_price,MAX(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.price end) as end_cost_price,MIN(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.price end) as first_cost_price,ifnull(g.label ,"") as label,convert(MIN(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.price end) * 10/g.market_price,decimal(10,1)) as discount,bg.sort_order,ifnull(SUBSTRING(g.times,1,2 ),"") as ftimes,ifnull(SUBSTRING(g.times,3 ),"") as ltimes')
            ->where('g.goods_id = gsp.goods_id and gsp.spec_3value = ss.storestock_id and s.store_id = g.store_id and gs.goods_id = g.goods_id and g.goods_id = bg.goods_id '.$conditions)
            ->page(I('request.page', 1, 'intval') . ',10')
            ->group('g.goods_id')
            ->having('is_exist = "true"')
//            ->order('is_exist desc,'.$sort . ' ' . $order.',mall_sort_order asc')
            ->order($sort . ' ' . $order.$sign.'bg.sort_order ASC,ifnull(SUBSTRING(g.times,1,2 ),"") DESC,ifnull(SUBSTRING(g.times,3 ),"") ASC')
            ->buildSql();
        $goods_list = M('discount')->alias('d')
            ->field("cc.store_id as sto_id,ifnull(cc.ico ,'') as ico,gl.*")
            ->join('right join '.$list.' gl on d.goods_id = gl.goods_id')
            ->join('left join ecm_coupon_codes cc on d.coupon_codes_id = cc.id and cc.enabled = 1')
            ->group('gl.goods_id')
//            ->order($sort . ' ' . $order)
            ->order($sort . ' ' . $order.$sign.'gl.sort_order ASC,ifnull(SUBSTRING(gl.times,1,2 ),"") DESC,ifnull(SUBSTRING(gl.times,3 ),"") ASC')
//            ->where(array('cc.enabled'=>1))
            ->select();
        if($_POST['token']){
            $res_token = M('app_token')->where(array('token'=>$_POST['token']))->find();
            $res_user = M('member')->where(array('user_id'=>$res_token['user_id']))->find();
        }

        foreach ($goods_list as $k => $v) {
            //年代
            if($v['times']) {
                $temp_times = substr($v['times'],2,strlen($v['times'])-1);
                $goods_list[$k]['times_label'] = (int)$temp_times <= 2015 ? '过季特卖': '';
            }else{
                $goods_list[$k]['times_label'] = '';
            }
            //折扣
            if($v['discount']) {
                if ($v['discount'] > 3.5 && $v['discount'] < 6){
                    $goods_list[$k]['discount_label'] = '折扣';
                }else if($v['discount'] < 3.5 && $v['discount'] > 0){
                    $goods_list[$k]['discount_label'] = '清仓';
                }else{
                    $goods_list[$k]['discount_label'] = '';
                }
            }else{
                $goods_list[$k]['discount_label'] = '';
            }
            //
            if($v['label'] == '正常'){
                $goods_list[$k]['label'] = '';
            }
            //按尺码分组
            $list_a = M('goods')
                ->table('ecm_goods g,ecm_goods_spec gsp,ecm_storestock ss,ecm_store s,ecm_goods_statistics gs')
                ->field('gsp.spec_2,group_concat(gsp.stock) as stocks,group_concat(gsp.spec_2) as spec_2s,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist')
                ->where('g.goods_id = gsp.goods_id and gsp.spec_3value = ss.storestock_id and s.store_id = g.store_id and gs.goods_id = g.goods_id and g.goods_id='.$v['goods_id'])
                ->group('gsp.spec_2')
                ->having('is_exist = "true"')
//            ->order('is_exist desc,'.$sort . ' ' . $order.',mall_sort_order asc')
                ->select();
            $arr = array_column($list_a,'spec_2');
            //尺码排序
            //1.先把数字排前面
            $arr_num = $arr ? $this->array_number_second($arr) : array();
            sort($arr_num);
            //2.按照尺码表取数字
            $arr_str = M('size_order')->group('size_name')->order('size_order asc')->select();
            $arr_str ? $arra_str = array_column($arr_str,'size_name') : array();
            //按顺序取出
            $arrs = $this->array_sort_second($arra_str,$arr);
            //数组合并
            $goods_list[$k]['spec_2s'] = array_merge($arr_num,$arrs);
            //按发货地分组
            $list_b = M('goods')
                ->table('ecm_goods g,ecm_goods_spec gsp,ecm_storestock ss,ecm_store s,ecm_goods_statistics gs')
                ->field('gsp.spec_2,ss.stock_name,group_concat(gsp.stock) as stocks,group_concat(gsp.spec_2) as spec_2s,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist')
                ->where('g.goods_id = gsp.goods_id and gsp.spec_3value = ss.storestock_id and s.store_id = g.store_id and gs.goods_id = g.goods_id and g.goods_id='.$v['goods_id'])
                ->group('ss.storestock_id')
                ->having('is_exist = "true"')
//            ->order('is_exist desc,'.$sort . ' ' . $order.',mall_sort_order asc')
                ->select();

            //发货地排序
            $array_unset = $this->array_unset_second($list_b,'stock_name');
            $arr = array_column($array_unset,'stock_name');
            $arrv = $this->array_sort_second(array( 0 => '境内仓',
                1 => '天津保税仓',
                2 => '香港直邮仓',
                3 => '海外直邮仓'),$arr);
            $goods_list[$k]['stock_names'] = $arrv;

            if ($v['sto_id'] && $_POST['token'] && $res_user){
                $res_store_goods = M('store')->where(array('store_id'=>$v['sto_id']))->find();
                $res_store_user = M('store')->where(array('store_id'=>$res_user['s_id']))->find();
                $res_region_goods = M('region')->where(array('region_id'=>$res_store_goods['region_id']))->find();
                $res_region_user = M('region')->where(array('region_id'=>$res_store_user['region_id']))->find();
                if($res_region_user['region_id'] == $res_region_goods['region_id'] || $res_region_user['parent_id'] == $res_region_goods['region_id'] || $res_region_user['region_id'] == $res_region_goods['parent_id']){
                    //显示优惠价
                    $goods_list[$k]['first_price'] = ($v['first_discount_price'] < $v['first_cost_price']) && $v['first_discount_price'] ? $v['first_discount_price'] : $v['first_cost_price'];
//                    $goods_list[$k]['end_price'] = ($v['end_discount_price'] < $v['end_cost_price']) && $v['end_discount_price'] ? $v['end_discount_price'] : $v['end_cost_price'];
                    $goods_list[$k]['end_price'] = $goods_list[$k]['first_price'];
                }else{
                    //显示普通价
                    $goods_list[$k]['first_price'] = $v['first_cost_price'];
//                    $goods_list[$k]['end_price'] = $v['end_cost_price'];
                    $goods_list[$k]['end_price'] = $goods_list[$k]['first_price'];
                    $goods_list[$k]['ico'] = '';
                }
            }else if(strlen($v['sto_id']) && $v['sto_id'] == '0'){
                //显示优惠价
                $goods_list[$k]['first_price'] = ($v['first_discount_price'] < $v['first_cost_price']) && $v['first_discount_price'] ? $v['first_discount_price'] : $v['first_cost_price'];
//                $goods_list[$k]['end_price'] = ($v['end_discount_price'] < $v['end_cost_price']) && $v['end_discount_price'] ? $v['end_discount_price'] : $v['end_cost_price'];
                $goods_list[$k]['end_price'] = $goods_list[$k]['first_price'];
            }else{
                //显示普通价
                $goods_list[$k]['first_price'] = $v['first_cost_price'];
//                $goods_list[$k]['end_price'] = $v['end_cost_price'];
                $goods_list[$k]['end_price'] = $goods_list[$k]['first_price'];
                $goods_list[$k]['ico'] = '';
            }
        }
        //总筛选
        $res_sort = M('goods')
            ->table('ecm_goods g,ecm_store s,ecm_goods_spec gsp,ecm_storestock as ss')
            ->field('g.cate_name,substring_index(g.cate_name," ",1) as parent_name,count(substring_index(g.cate_name," ",1)) as num,group_concat(gsp.stock) as stocks,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist,g.sex,g.brand,gsp.spec_1value,gsp.spec_2,g.material,ss.stock_name')
            ->where('g.store_id = s.store_id AND g.goods_id = gsp.goods_id AND gsp.spec_3value = ss.storestock_id'.$conditions)
            ->group('g.goods_id')
            ->order('count(substring_index(g.cate_name," ",1)) desc')
            ->having('is_exist = "true"')
            ->select();

        //筛选 按尺码
        $res_sort_spec_2 = M('goods')
            ->table('ecm_goods g,ecm_store s,ecm_goods_spec gsp,ecm_storestock as ss')
            ->field('g.cate_name,substring_index(g.cate_name," ",1) as parent_name,count(substring_index(g.cate_name," ",1)) as num,group_concat(gsp.stock) as stocks,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist,g.sex,g.brand,gsp.spec_1value,gsp.spec_2,g.material,ss.stock_name')
            ->where('g.store_id = s.store_id AND g.goods_id = gsp.goods_id AND gsp.spec_3value = ss.storestock_id'.$conditions)
            ->group('gsp.spec_2')
            ->having('is_exist = "true"')
            ->select();
        //筛选 按颜色
        $res_sort_spec_1value = M('goods')
            ->table('ecm_goods g,ecm_store s,ecm_goods_spec gsp,ecm_storestock as ss')
            ->field('g.cate_name,substring_index(g.cate_name," ",1) as parent_name,count(substring_index(g.cate_name," ",1)) as num,group_concat(gsp.stock) as stocks,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist,g.sex,g.brand,gsp.spec_1value,gsp.spec_2,g.material,ss.stock_name')
            ->where('g.store_id = s.store_id AND g.goods_id = gsp.goods_id AND gsp.spec_3value = ss.storestock_id'.$conditions)
            ->group('gsp.spec_1value')
            ->having('is_exist = "true"')
            ->select();
        //筛选 按仓库
        $res_sort_stock_name = M('goods')
            ->table('ecm_goods g,ecm_store s,ecm_goods_spec gsp,ecm_storestock as ss')
            ->field('g.cate_name,substring_index(g.cate_name," ",1) as parent_name,count(substring_index(g.cate_name," ",1)) as num,group_concat(gsp.stock) as stocks,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist,g.sex,g.brand,gsp.spec_1value,gsp.spec_2,g.material,ss.stock_name')
            ->where('g.store_id = s.store_id AND g.goods_id = gsp.goods_id AND gsp.spec_3value = ss.storestock_id'.$conditions)
            ->group('ss.stock_name')
//            ->order('count(substring_index(g.cate_name," ",1)) desc')
            ->having('is_exist = "true"')
            ->select();

        //二级筛选
        $array_second = array();
        //性别
        //text 名称 value 值 key 返回字段 type 类型(0,1,2) num 数量 is_single 是否复选(true,false) choose 最多可选
        $array_unset= $this->array_unset_second($res_sort,'sex');
        $arr = array_column($array_unset,'sex');
        $arrv = $this->array_sort_second(array('女','男','儿童','中性'),$arr);
        $array_second [] = array(
            'text' => '性别',
            'value' => $arrv,
            'key' => 'sex',
            'type' => 0,
            'num' => 0,
            'is_single' => false,
            'choose' => '4'
        );
        //品牌
        $array_unset = $this->array_unset_second($res_sort,'brand');
        $arr = array_column($array_unset,'brand');
        sort($arr);
        $arrs = $this->array_sort_second(array('HERMES', 'GUCCI', 'BURBERRY', 'OFF WHITE', 'KENZO', 'VALENTINO', 'CANADA GOOSE', 'MSGM', 'BALENCIAGA'),$arr);
        $arrss = $this->array_unset_sort_second($arrs,$arr);
        $arrv = $arrs ? array_merge($arrs,$arrss) : $arrss;
        $array_second [] = array(
            'text' => '品牌',
            'value' => $arrv,
            'key' => 'brands',
            'type' => 1,
            'num' => 9,
            'is_single' => false,
            'choose' => '5'
        );
        //分类
        $array_unset = $this->array_unset_second($res_sort,'parent_name');
        $arr = array_column($array_unset,'parent_name');
        $array_second [] = array(
            'text' => '分类',
            'value' => $arr,
            'key' => 'cate_names',
            'type' => 1,
            'num' => 9,
            'is_single' => false,
            'choose' => '5'
        );
        //价格
        $array_second [] = array(
            'text' => '价格',
            'value' => array('0-1000','1000-2000','2000-4000','4000-8000','8000-15000','15000-0'),
            'key' => 'price',
            'type' => 2,
            'num' => 0,
            'is_single' => true,
            'choose' => '1'
        );
        //尺码
        $array_unset = $this->array_unset_second($res_sort_spec_2,'spec_2');
        $arr = array_column($array_unset,'spec_2');
        //尺码排序
        //1.先把数字排前面
        $arr ? $arr_num = $this->array_number_second($arr) : array();
        sort($arr_num);
        //2.按照尺码表取数字
        $arr_str = M('size_order')->order('mode_id asc,size_order asc')->group('size_name')->select();
        $arr_str ? $arra_str = array_column($arr_str,'size_name') : array();
        //按顺序取出
        $arrs = $this->array_sort_second($arra_str,$arr);
        //数组合并
        $arrv = array_merge($arr_num,$arrs);
        //
        $array_second [] = array(
            'text' => '尺码',
            'value' => $arrv,
            'key' => 'spec_2',
            'type' => 1,
            'num' => 9,
            'is_single' => false,
            'choose' => '5'
        );
        //颜色
        $array_unset = $this->array_unset_second($res_sort_spec_1value,'spec_1value');
        $arr = array_column($array_unset,'spec_1value');
        $array_second [] = array(
            'text' => '颜色',
            'value' => $arr,
            'key' => 'spec_1value',
            'type' => 1,
            'num' => 0,
            'is_single' => false,
            'choose' => '5'
        );
        //材质 暂时取消
//        $array_unset = $this->array_unset_second($res_sort,'material');
//        $arr = array_column($array_unset,'material');
//        $array_second [] = array(
//            'k' => array('材质'),
//            'v' => $arr,
//            'c' => array('material'),
//        );
        //发货地
        $array_unset = $this->array_unset_second($res_sort_stock_name,'stock_name');
        $arr = array_column($array_unset,'stock_name');
        $arrv = $this->array_sort_second(array( 0 => '境内仓',
            1 => '天津保税仓',
            2 => '香港直邮仓',
            3 => '海外直邮仓'),$arr);
        $array_second [] = array(
            'text' => '发货地',
            'value' => $arrv,
            'key' => 'stock_name',
            'type' => 1,
            'num' => 0,
            'is_single' => false,
            'choose' => '4'
        );
        //排序
        //关闭exist
//        if (!in_array( I('request.sort'), array('sales', 'price', 'add_time', 'comments')) && !in_array(I('request.order'), array('desc', 'asc'))) {
//            $last_names = array_column($goods_list,'is_exist');
//            array_multisort($last_names,SORT_DESC,$goods_list);
//        }
//        $_POST['user_id'] = 3;
        if($_POST['user_id']){
            $cond_collect['user_id'] = $_POST['user_id'];
            $res_collect = M('collect')->where($cond_collect)->field('item_id as goods_id ,user_id')->select();
            foreach ($goods_list as $key => $value){
                $res_spec = M('goods_spec')->group('spec_1value')->where(array('goods_id'=>$value['goods_id']))->field('spec_1')->select();
                $data = array_column($res_spec,'spec_1');
                $goods_list[$key]['spec'] = $data;
                if($res_collect){
                    if(in_array($goods_list[$key]['goods_id'],array_column($res_collect,'goods_id'))){
                        $goods_list[$key]['collect'] = true;
                    }else{
                        $goods_list[$key]['collect'] = false;
                    }
//                    if($goods_list[$key]['goods_id'] == 21){
//                        var_dump($goods_list[$key]['collect']);exit;
//                    }
                }else{
                    $goods_list[$key]['collect'] = false;
                }
            }
        }else{
            foreach ($goods_list as $key => $value){
                $res_spec = M('goods_spec')->group('spec_1value')->where(array('goods_id'=>$value['goods_id']))->field('spec_1')->select();
                $data = array_column($res_spec,'spec_1');
                $goods_list[$key]['spec'] = $data;
            }
        }
        /*
        if ($goods_list) {
            foreach ($goods_list as $key => $goods) {
                $goods_list[$key]['price'] = D('Promotion')->get_promotion_price($goods['goods_id'], $goods['spec_id']);
            }
        }
         */
        if(!$goods_list){
            $goods_list = array();
        }
        $res = M('banner_setting')->where(array('type_id'=>2))->select();
        $data = array(
            'goods_list' => $goods_list,
            'banner' => $res,
            'cate' => array(),
            'second' => $array_second
        );
        render('10000', 'OK', $data);

    }

    function get_theme(){
        if(!$_POST['theme_id']){
            render('10004', '参数错误');
        }
        $where['theme_id'] = $_POST['theme_id'];
        $where['theme_title'] = $_POST['theme_id'];
        $where['_logic'] = 'or';
        $cond['_complex'] = $where;   //or条
        $res = M('theme_setting')->where($cond)->find();
        if(!$res){
            render('10004', '参数错误');
        }
        //redis
        set_redis('hot_theme',$res['theme_title']);
        //zRevRangeByScore 分数排行
        //var_dump($redis ->zRevRangeByScore('hot_theme','+inf','-inf'));
        //

//        $cond['goods_id'] = array('IN',$res['goods_id']);
        //筛选商品id
//        $conditions = ' AND g.goods_id IN ('.$res['goods_id'].') AND g.if_show=1 AND g.closed=0';
        //标签分类
        //goods_id
        $conditions = ' AND g.if_show=1 AND g.closed=0';
        $goods_id = I('request.goods_id', '');
        if(trim($goods_id)){
            $conditions .= ' AND g.goods_id IN ('.$goods_id.')';
        }
        //theme_id
        $theme_id= I('request.theme_id', '');
        if(trim($theme_id)){
            $res_theme = M('theme_goods')->where(array('theme_id'=>$theme_id))->select();
            if($res_theme){
                $res_temp_array = array_column($res_theme,'goods_id');
                $res_temp_str = implode(',',$res_temp_array);
                $conditions .= ' AND g.goods_id IN ('.$res_temp_str.')';
            }
        }
        $cate = I('request.cate', '');
        if ($cate) {
            $conditions .= ' AND cate_name LIKE "%'.$cate.'%"';
        }
        //排序
        $sort = I('request.sort', '');
        $order = I('request.order', '');
        $sign = ',';
        if (!in_array($sort, array('sales', 'price', 'add_time', 'comments', 'discount'))) {
            $sort = '';
            $sign = '';
        }
        if (!in_array($order, array('desc', 'asc'))) {
            $order = '';
        }
        if($sort == 'price'){
            $sort = 'first_cost_price';
        }

        if($_POST['sex']){
            $arr = explode(',',$_POST['sex']);
            foreach ($arr as $key=>$value){
                $arr[$key] = '"'. $arr[$key] . '"';
            }
            $str = implode(',',$arr);
            $conditions .= ' AND g.sex IN('.$str.')';
        }
        if($_POST['brands']){
            $arr = explode(',',$_POST['brands']);
            foreach ($arr as $key=>$value){
                $arr[$key] = '"'. $arr[$key] . '"';
            }
            $str = implode(',',$arr);
            $conditions .= ' AND g.brand IN('.$str.')';
        }
        if($_POST['cate_names']){
            $temp_cate = explode(',',$_POST['cate_names']);
            foreach ($temp_cate as $k => $v){
                if($k == 0 && $k == count($temp_cate) - 1){
                    $conditions .= ' AND (g.cate_name LIKE "%'.$v.'%")';
                }else if($k == 0){
                    $conditions .= ' AND (g.cate_name LIKE "%'.$v.'%"';
                }else if($k == count($temp_cate) - 1){
                    $conditions .= ' OR g.cate_name LIKE "%'.$v.'%")';
                }else{
                    $conditions .= ' OR g.cate_name LIKE "%'.$v.'%"';
                }
            }
        }
        if($_POST['price']){
            $tn_arr = explode('-',$_POST['price']);
            if(!$tn_arr[1]){
                $conditions .= ' AND gsp.price>='.$tn_arr[0];
            }else{
                $conditions .= ' AND gsp.price>='.$tn_arr[0].' AND gsp.price<='.$tn_arr[1];
            }
        }
        if($_POST['spec_2']){
            $arr = explode(',',$_POST['spec_2']);
            foreach ($arr as $key=>$value){
                $arr[$key] = '"'. $arr[$key] . '"';
            }
            $str = implode(',',$arr);
            $conditions .= ' AND gsp.spec_2 IN('.$str.')';
        }
        if($_POST['spec_1value']){
            $arr = explode(',',$_POST['spec_1value']);
            foreach ($arr as $key=>$value){
                $arr[$key] = '"'. $arr[$key] . '"';
            }
            $str = implode(',',$arr);
            $conditions .= ' AND gsp.spec_1value IN('.$str.')';
        }
        if($_POST['stock_name']){
            $arr = explode(',',$_POST['stock_name']);
            foreach ($arr as $key=>$value){
                $arr[$key] = '"'. $arr[$key] . '"';
            }
            $str = implode(',',$arr);
            $conditions .= ' AND ss.stock_name IN('.$str.')';
        }
        $conditions1 = $conditions;
        if(trim($theme_id)){
           $conditions1 .= ' AND tg.theme_id ='.$theme_id;
        }
        $list = M('goods')
            ->table('ecm_goods g,ecm_goods_spec gsp,ecm_storestock ss,ecm_store s,ecm_goods_statistics gs,ecm_theme_goods tg')
            ->field('g.brand,g.goods_id,g.store_id,g.goods_name,g.default_image,g.price,g.times,g.market_price,gs.comments,g.add_time,group_concat(gsp.stock) as stocks,group_concat(gsp.spec_2) as spec_2s,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist, MAX(case when gsp.stock=0 or gsp.price=0.00 or gsp.discount_price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.discount_price end) as end_discount_price, MIN(case when gsp.stock=0 or gsp.price=0.00 or gsp.discount_price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.discount_price end) as first_discount_price,MAX(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.price end) as end_cost_price,MIN(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.price end) as first_cost_price,ifnull(g.label ,"") as label,convert(MIN(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.price end) * 10/g.market_price,decimal(10,1)) as discount,tg.sort_order,tg.theme_id,ifnull(SUBSTRING(g.times,1,2 ),"") as ftimes,ifnull(SUBSTRING(g.times,3 ),"") as ltimes')
            ->where('g.goods_id = gsp.goods_id and gsp.spec_3value = ss.storestock_id and s.store_id = g.store_id and gs.goods_id = g.goods_id and g.goods_id = tg.goods_id '.$conditions1)
            ->page(I('request.page', 1, 'intval') . ',10')
            ->group('g.goods_id')
            ->having('is_exist = "true"')
//            ->order('is_exist desc,'.$sort . ' ' . $order.',mall_sort_order asc')
            ->order($sort . ' ' . $order.$sign.'tg.sort_order ASC,ifnull(SUBSTRING(g.times,3 ),"") DESC,ifnull(SUBSTRING(g.times,1,2 ),"") ASC')
            ->buildSql();
        $goods_list = M('discount')->alias('d')
            ->field("cc.store_id as sto_id,ifnull(cc.ico ,'') as ico,gl.*")
            ->join('right join '.$list.' gl on d.goods_id = gl.goods_id')
            ->join('left join ecm_coupon_codes cc on d.coupon_codes_id = cc.id and cc.enabled = 1')
            ->group('gl.goods_id')
//            ->order($sort . ' ' . $order)
            ->order($sort . ' ' . $order.$sign.'gl.sort_order ASC,ifnull(SUBSTRING(gl.times,3 ),"") DESC,ifnull(SUBSTRING(gl.times,1,2 ),"") ASC')
//            ->where(array('cc.enabled'=>1))
            ->select();
//        $res_goods = M('goods')->limit($_POST['pagenum'])->page($_POST['page'])->where($cond)->select();
//        foreach ($res_goods as $key => $value) {
//            $res_goods[$key]['is_exist'] = D('goods')->get_isSaled($value['goods_id']);
//        }
        //总筛选
        $res_sort = M('goods')
            ->table('ecm_goods g,ecm_store s,ecm_goods_spec gsp,ecm_storestock as ss')
            ->field('g.cate_name,substring_index(g.cate_name," ",1) as parent_name,count(substring_index(g.cate_name," ",1)) as num,group_concat(gsp.stock) as stocks,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist,g.sex,g.brand,gsp.spec_1value,gsp.spec_2,g.material,ss.stock_name')
            ->where('g.store_id = s.store_id AND g.goods_id = gsp.goods_id AND gsp.spec_3value = ss.storestock_id'.$conditions)
            ->group('g.goods_id')
            ->order('count(substring_index(g.cate_name," ",1)) desc')
            ->having('is_exist = "true"')
            ->select();

        //筛选 按尺码
        $res_sort_spec_2 = M('goods')
            ->table('ecm_goods g,ecm_store s,ecm_goods_spec gsp,ecm_storestock as ss')
            ->field('g.cate_name,substring_index(g.cate_name," ",1) as parent_name,count(substring_index(g.cate_name," ",1)) as num,group_concat(gsp.stock) as stocks,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist,g.sex,g.brand,gsp.spec_1value,gsp.spec_2,g.material,ss.stock_name')
            ->where('g.store_id = s.store_id AND g.goods_id = gsp.goods_id AND gsp.spec_3value = ss.storestock_id'.$conditions)
            ->group('gsp.spec_2')
            ->having('is_exist = "true"')
            ->select();
        //筛选 按颜色
        $res_sort_spec_1value = M('goods')
            ->table('ecm_goods g,ecm_store s,ecm_goods_spec gsp,ecm_storestock as ss')
            ->field('g.cate_name,substring_index(g.cate_name," ",1) as parent_name,count(substring_index(g.cate_name," ",1)) as num,group_concat(gsp.stock) as stocks,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist,g.sex,g.brand,gsp.spec_1value,gsp.spec_2,g.material,ss.stock_name')
            ->where('g.store_id = s.store_id AND g.goods_id = gsp.goods_id AND gsp.spec_3value = ss.storestock_id'.$conditions)
            ->group('gsp.spec_1value')
            ->having('is_exist = "true"')
            ->select();
        //筛选 按仓库
        $res_sort_stock_name = M('goods')
            ->table('ecm_goods g,ecm_store s,ecm_goods_spec gsp,ecm_storestock as ss')
            ->field('g.cate_name,substring_index(g.cate_name," ",1) as parent_name,count(substring_index(g.cate_name," ",1)) as num,group_concat(gsp.stock) as stocks,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist,g.sex,g.brand,gsp.spec_1value,gsp.spec_2,g.material,ss.stock_name')
            ->where('g.store_id = s.store_id AND g.goods_id = gsp.goods_id AND gsp.spec_3value = ss.storestock_id'.$conditions)
            ->group('ss.stock_name')
//            ->order('count(substring_index(g.cate_name," ",1)) desc')
            ->having('is_exist = "true"')
            ->select();

        //二级筛选
        $array_second = array();
        //性别
        //text 名称 value 值 key 返回字段 type 类型(0,1,2) num 数量 is_single 是否复选(true,false) choose 最多可选
        $array_unset= $this->array_unset_second($res_sort,'sex');
        $arr = array_column($array_unset,'sex');
        $arrv = $this->array_sort_second(array('女','男','儿童','中性'),$arr);
        $array_second [] = array(
            'text' => '性别',
            'value' => $arrv,
            'key' => 'sex',
            'type' => 0,
            'num' => 0,
            'is_single' => false,
            'choose' => '4'
        );
        //品牌
        $array_unset = $this->array_unset_second($res_sort,'brand');
        $arr = array_column($array_unset,'brand');
        sort($arr);
        $arrs = $this->array_sort_second(array('HERMES', 'GUCCI', 'BURBERRY', 'OFF WHITE', 'KENZO', 'VALENTINO', 'CANADA GOOSE', 'MSGM', 'BALENCIAGA'),$arr);
        $arrss = $this->array_unset_sort_second($arrs,$arr);
        $arrv = $arrs ? array_merge($arrs,$arrss) : $arrss;
        $array_second [] = array(
            'text' => '品牌',
            'value' => $arrv,
            'key' => 'brands',
            'type' => 1,
            'num' => 9,
            'is_single' => false,
            'choose' => '5'
        );
        //分类
        $array_unset = $this->array_unset_second($res_sort,'parent_name');
        $arr = array_column($array_unset,'parent_name');
        $array_second [] = array(
            'text' => '分类',
            'value' => $arr,
            'key' => 'cate_names',
            'type' => 1,
            'num' => 9,
            'is_single' => false,
            'choose' => '5'
        );
        //价格
        $array_second [] = array(
            'text' => '价格',
            'value' => array('0-1000','1000-2000','2000-4000','4000-8000','8000-15000','15000-0'),
            'key' => 'price',
            'type' => 2,
            'num' => 0,
            'is_single' => true,
            'choose' => '1'
        );
        //尺码
        $array_unset = $this->array_unset_second($res_sort_spec_2,'spec_2');
        $arr = array_column($array_unset,'spec_2');
        //尺码排序
        //1.先把数字排前面
        $arr ? $arr_num = $this->array_number_second($arr) : array();
        sort($arr_num);
        //2.按照尺码表取数字
        $arr_str = M('size_order')->order('mode_id asc,size_order asc')->group('size_name')->select();
        $arr_str ? $arra_str = array_column($arr_str,'size_name') : array();
        //按顺序取出
        $arrs = $this->array_sort_second($arra_str,$arr);
        //数组合并
        $arrv = array_merge($arr_num,$arrs);
        //
        $array_second [] = array(
            'text' => '尺码',
            'value' => $arrv,
            'key' => 'spec_2',
            'type' => 1,
            'num' => 9,
            'is_single' => false,
            'choose' => '5'
        );
        //颜色
        $array_unset = $this->array_unset_second($res_sort_spec_1value,'spec_1value');
        $arr = array_column($array_unset,'spec_1value');
        $array_second [] = array(
            'text' => '颜色',
            'value' => $arr,
            'key' => 'spec_1value',
            'type' => 1,
            'num' => 0,
            'is_single' => false,
            'choose' => '5'
        );
        //材质 暂时取消
//        $array_unset = $this->array_unset_second($res_sort,'material');
//        $arr = array_column($array_unset,'material');
//        $array_second [] = array(
//            'k' => array('材质'),
//            'v' => $arr,
//            'c' => array('material'),
//        );
        //发货地
        $array_unset = $this->array_unset_second($res_sort_stock_name,'stock_name');
        $arr = array_column($array_unset,'stock_name');
        $arrv = $this->array_sort_second(array( 0 => '境内仓',
            1 => '天津保税仓',
            2 => '香港直邮仓',
            3 => '海外直邮仓'),$arr);
        $array_second [] = array(
            'text' => '发货地',
            'value' => $arrv,
            'key' => 'stock_name',
            'type' => 1,
            'num' => 0,
            'is_single' => false,
            'choose' => '4'
        );

        if($_POST['token']){
            $res_token = M('app_token')->where(array('token'=>$_POST['token']))->find();
            $res_user = M('member')->where(array('user_id'=>$res_token['user_id']))->find();
        }
        foreach ($goods_list as $k => $v) {
            //年代
            if($v['times']) {
                $temp_times = substr($v['times'],2,strlen($v['times'])-1);
                $goods_list[$k]['times_label'] = (int)$temp_times <= 2015 ? '过季特卖': '';
            }else{
                $goods_list[$k]['times_label'] = '';
            }
            //折扣
            if($v['discount']) {
                if ($v['discount'] > 3.5 && $v['discount'] < 6){
                    $goods_list[$k]['discount_label'] = '折扣';
                }else if($v['discount'] < 3.5 && $v['discount'] > 0){
                    $goods_list[$k]['discount_label'] = '清仓';
                }else{
                    $goods_list[$k]['discount_label'] = '';
                }
            }else{
                $goods_list[$k]['discount_label'] = '';
            }
            if($v['label'] == '正常'){
                $goods_list[$k]['label'] = '';
            }
            $list_a = M('goods')
                ->table('ecm_goods g,ecm_goods_spec gsp,ecm_storestock ss,ecm_store s,ecm_goods_statistics gs')
                ->field('gsp.spec_2,group_concat(gsp.stock) as stocks,group_concat(gsp.spec_2) as spec_2s,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist')
                ->where('g.goods_id = gsp.goods_id and gsp.spec_3value = ss.storestock_id and s.store_id = g.store_id and gs.goods_id = g.goods_id and g.goods_id='.$v['goods_id'])
                ->group('gsp.spec_2')
                ->having('is_exist = "true"')
//            ->order('is_exist desc,'.$sort . ' ' . $order.',mall_sort_order asc')
                ->select();
            $arr = array_column($list_a,'spec_2');
            //尺码排序
            //1.先把数字排前面
            $arr_num = $arr ? $this->array_number_second($arr) : array();
            sort($arr_num);
            //2.按照尺码表取数字
            $arr_str = M('size_order')->group('size_name')->order('size_order asc')->select();
            $arr_str ? $arra_str = array_column($arr_str,'size_name') : array();
            //按顺序取出
            $arrs = $this->array_sort_second($arra_str,$arr);
            //数组合并
            $goods_list[$k]['spec_2s'] = array_merge($arr_num,$arrs);
            //按发货地分组
            $list_b = M('goods')
                ->table('ecm_goods g,ecm_goods_spec gsp,ecm_storestock ss,ecm_store s,ecm_goods_statistics gs')
                ->field('gsp.spec_2,ss.stock_name,group_concat(gsp.stock) as stocks,group_concat(gsp.spec_2) as spec_2s,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist')
                ->where('g.goods_id = gsp.goods_id and gsp.spec_3value = ss.storestock_id and s.store_id = g.store_id and gs.goods_id = g.goods_id and g.goods_id='.$v['goods_id'])
                ->group('ss.storestock_id')
                ->having('is_exist = "true"')
//            ->order('is_exist desc,'.$sort . ' ' . $order.',mall_sort_order asc')
                ->select();

            //发货地排序
            $array_unset = $this->array_unset_second($list_b,'stock_name');
            $arr = array_column($array_unset,'stock_name');
            $arrv = $this->array_sort_second(array( 0 => '境内仓',
                1 => '天津保税仓',
                2 => '香港直邮仓',
                3 => '海外直邮仓'),$arr);
            $goods_list[$k]['stock_names'] = $arrv;
            if ($v['sto_id'] && $_POST['token'] && $res_user){
                $res_store_goods = M('store')->where(array('store_id'=>$v['sto_id']))->find();
                $res_store_user = M('store')->where(array('store_id'=>$res_user['s_id']))->find();
                $res_region_goods = M('region')->where(array('region_id'=>$res_store_goods['region_id']))->find();
                $res_region_user = M('region')->where(array('region_id'=>$res_store_user['region_id']))->find();
                if($res_region_user['region_id'] == $res_region_goods['region_id'] || $res_region_user['parent_id'] == $res_region_goods['region_id'] || $res_region_user['region_id'] == $res_region_goods['parent_id']){
                    //显示优惠价
                    $goods_list[$k]['first_price'] = ($v['first_discount_price'] < $v['first_cost_price']) && $v['first_discount_price'] ? $v['first_discount_price'] : $v['first_cost_price'];
//                    $goods_list[$k]['end_price'] = ($v['end_discount_price'] < $v['end_cost_price']) && $v['end_discount_price'] ? $v['end_discount_price'] : $v['end_cost_price'];
                    $goods_list[$k]['end_price'] = $goods_list[$k]['first_price'];
                }else{
                    //显示普通价
                    $goods_list[$k]['first_price'] = $v['first_cost_price'];
//                    $goods_list[$k]['end_price'] = $v['end_cost_price'];
                    $goods_list[$k]['end_price'] = $goods_list[$k]['first_price'];
                    $goods_list[$k]['ico'] = '';
                }
            }else if(strlen($v['sto_id']) && $v['sto_id'] == '0'){
                //显示优惠价
                $goods_list[$k]['first_price'] = ($v['first_discount_price'] < $v['first_cost_price']) && $v['first_discount_price'] ? $v['first_discount_price'] : $v['first_cost_price'];
//                $goods_list[$k]['end_price'] = ($v['end_discount_price'] < $v['end_cost_price']) && $v['end_discount_price'] ? $v['end_discount_price'] : $v['end_cost_price'];
                $goods_list[$k]['end_price'] = $goods_list[$k]['first_price'];
            }else{
                //显示普通价
                $goods_list[$k]['first_price'] = $v['first_cost_price'];
//                $goods_list[$k]['end_price'] = $v['end_cost_price'];
                $goods_list[$k]['end_price'] = $goods_list[$k]['first_price'];
                $goods_list[$k]['ico'] = '';
            }
        }
        if($_POST['user_id']){
            $cond_collect['user_id'] = $_POST['user_id'];
            $cond_collect['item_id'] = array('IN',$res['goods_id']);
            $res_collect = M('collect')->where($cond_collect)->field('item_id as goods_id ,user_id')->select();
            foreach ($goods_list as $key => $value){
                $res_spec = M('goods_spec')->group('spec_1value')->where(array('goods_id'=>$value['goods_id']))->field('spec_1')->select();
                $data = array_column($res_spec,'spec_1');
                $goods_list[$key]['spec'] = $data;
                if($res_collect){
                    foreach ($res_collect as $k => $v) {
                        if(!$goods_list[$key]['collect']){
                            if($value['goods_id'] == $v['goods_id']){
                                $goods_list[$key]['collect'] = true;
                            }else{
                                $goods_list[$key]['collect'] = false;
                            }
                        }
                    }
                }else{
                    $goods_list[$key]['collect'] = false;
                }
            }
        }else{
            foreach ($goods_list as $key => $value){
                $res_spec = M('goods_spec')->group('spec_1value')->where(array('goods_id'=>$value['goods_id']))->field('spec_1')->select();
                $data = array_column($res_spec,'spec_1');
                $goods_list[$key]['spec'] = $data;
            }
        }
        $data = array(
            'theme' => $res,
            'goods' => $goods_list,
            'cate' => $data_sort ? $data_sort : array(),
            'second' => $array_second
        );
        render('10000', 'OK', $data);
    }

    function limitedtime_list(){
        if(!$_POST['page'] || !$_POST['pagenum']){
            render('10000', '参数错误');
        }
        $cond['end_time'] = array('gt',date("Y-m-d H:i:s"));
        $res = M('limitedtime_setting')->where($cond)->limit($_POST['pagenum'])->page($_POST['page'])->order('sort_order desc')->select();
        if($res){
            foreach($res as $key => $value){
                $res[$key]['start_time'] = strtotime($value['start_time']);
                $res[$key]['end_time'] = strtotime($value['end_time']);
            }
        }else{
            render('10000', 'OK', json_decode('{}'));
        }

        render('10000', 'OK', array('data'=>$res));
    }

//    lichen 2019/5/30 end

    /**
     * @api {get} /index.php?m=Home&c=Index&a=get_userBanner 显示用户banner
     *
     */
    public function get_userBanner(){
        $resBanner = M('banner_setting')->where(array('type_id' => 4))->order('sort_order')->limit(5)->select();
        $data['banner'] = $resBanner;
        render('10000', '', $data);
    }

    /**
     * @api {get} /index.php?m=Home&c=Index&a=get_wishHomepage 显示心愿单列表
     *
     */
    function get_wishHomepage(){
        if(!I('request.page')){
            render('10004','参数错误');
        }
        $res_pic = M('limited_setting')->find();
        $conditions = ' AND g.if_show=1 AND g.closed=0 AND s.state=1';
        $conditions .= ' AND ss.stock_style=3';
        if($_POST['cate_name']){
              $conditions .= ' AND g.cate_name LIKE "%'.$_POST['cate_name'].'%"';
        }
        if($_POST['goods_id']){
            $conditions .= ' AND g.goods_id = '.$_POST['goods_id'];
        }
        $list = M('goods')
            ->table('ecm_goods g,ecm_goods_spec gsp,ecm_storestock ss,ecm_store s,ecm_goods_statistics gs')
            ->field('g.brand,g.goods_id,g.store_id,g.goods_name,g.times,g.default_image,g.mall_sort_order,g.price,g.market_price,gs.comments,g.add_time,group_concat(gsp.stock) as stocks,group_concat(gsp.spec_2) as spec_2s,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist, MAX(case when gsp.stock=0 or gsp.price=0.00 or gsp.discount_price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.discount_price end) as end_discount_price, MIN(case when gsp.stock=0 or gsp.price=0.00 or gsp.discount_price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.discount_price end) as first_discount_price,MAX(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.price end) as end_cost_price,MIN(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.price end) as first_cost_price,ifnull(g.label ,"") as label,convert(MIN(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.price end) * 10/g.market_price,decimal(10,1)) as discount')
            ->where('g.goods_id = gsp.goods_id and gsp.spec_3value = ss.storestock_id and s.store_id = g.store_id and gs.goods_id = g.goods_id and g.wish_close = 1'.$conditions)
            ->page(I('request.page', 1, 'intval') . ',10')
            ->group('g.goods_id')
            ->having('is_exist = "true"')
//            ->order('is_exist desc,'.$sort . ' ' . $order.',mall_sort_order asc')
            ->order('g.mall_sort_order asc, g.add_time')
            ->buildSql();
        $goods_list = M('discount')->alias('d')
            ->field("cc.store_id as sto_id,ifnull(cc.ico ,'') as ico,gl.*")
            ->join('right join '.$list.' gl on d.goods_id = gl.goods_id')
            ->join('left join ecm_coupon_codes cc on d.coupon_codes_id = cc.id and cc.enabled = 1')
            ->group('gl.goods_id')
            ->order('gl.mall_sort_order asc, gl.add_time')
//            ->where(array('cc.enabled'=>1))
            ->select();
        //临时取消心愿单
        $res_wish_close = M('mall_config')->field('code,value')->where(array('code'=>'wish_close'))->find();
        if($res_wish_close['value'] != 1){
            $data['wish_none_url'] = C('SITE_URL').'/data/files/wish/wish_none.jpg';
            render('10000', 'OK', $data);
        }
        if($_POST['token']){
            $res_token = M('app_token')->where(array('token'=>$_POST['token']))->find();
            $res_user = M('member')->where(array('user_id'=>$res_token['user_id']))->find();
        }
        foreach ($goods_list as $k => $v) {
            //年代
            if($v['times']) {
                $temp_times = substr($v['times'],2,strlen($v['times'])-1);
                $goods_list[$k]['times_label'] = (int)$temp_times <= 2015 ? '过季特卖': '';
            }else{
                $goods_list[$k]['times_label'] = '';
            }
            //折扣
            if($v['discount']) {
                if ($v['discount'] > 3.5 && $v['discount'] < 6){
                    $goods_list[$k]['discount_label'] = '折扣';
                }else if($v['discount'] < 3.5 && $v['discount'] > 0){
                    $goods_list[$k]['discount_label'] = '清仓';
                }else{
                    $goods_list[$k]['discount_label'] = '';
                }
            }else{
                $goods_list[$k]['discount_label'] = '';
            }
            if($v['label'] == '正常'){
                $goods_list[$k]['label'] = '';
            }
            $list_a = M('goods')
                ->table('ecm_goods g,ecm_goods_spec gsp,ecm_storestock ss,ecm_store s,ecm_goods_statistics gs')
                ->field('gsp.spec_2,group_concat(gsp.stock) as stocks,group_concat(gsp.spec_2) as spec_2s,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist')
                ->where('g.goods_id = gsp.goods_id and gsp.spec_3value = ss.storestock_id and s.store_id = g.store_id and gs.goods_id = g.goods_id and g.goods_id='.$v['goods_id'])
                ->group('gsp.spec_2')
                ->having('is_exist = "true"')
//            ->order('is_exist desc,'.$sort . ' ' . $order.',mall_sort_order asc')
                ->select();
            $arr = array_column($list_a,'spec_2');
            //尺码排序
            //1.先把数字排前面
            $arr_num = $arr ? $this->array_number_second($arr) : array();
            sort($arr_num);
            //2.按照尺码表取数字
            $arr_str = M('size_order')->group('size_name')->order('size_order asc')->select();
            $arr_str ? $arra_str = array_column($arr_str,'size_name') : array();
            //按顺序取出
            $arrs = $this->array_sort_second($arra_str,$arr);
            //数组合并
            $goods_list[$k]['spec_2s'] = array_merge($arr_num,$arrs);
            $list_b = M('goods')
                ->table('ecm_goods g,ecm_goods_spec gsp,ecm_storestock ss,ecm_store s,ecm_goods_statistics gs')
                ->field('gsp.spec_2,ss.stock_name,group_concat(gsp.stock) as stocks,group_concat(gsp.spec_2) as spec_2s,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist')
                ->where('g.goods_id = gsp.goods_id and gsp.spec_3value = ss.storestock_id and s.store_id = g.store_id and gs.goods_id = g.goods_id and g.goods_id='.$v['goods_id'])
                ->group('ss.storestock_id')
                ->having('is_exist = "true"')
//            ->order('is_exist desc,'.$sort . ' ' . $order.',mall_sort_order asc')
                ->select();

            //发货地排序
            $array_unset = $this->array_unset_second($list_b,'stock_name');
            $arr = array_column($array_unset,'stock_name');
            $arrv = $this->array_sort_second(array( 0 => '境内仓',
                1 => '天津保税仓',
                2 => '香港直邮仓',
                3 => '海外直邮仓'),$arr);
            $goods_list[$k]['stock_names'] = $arrv;

            if ($v['sto_id'] && $_POST['token'] && $res_user){
                $res_store_goods = M('store')->where(array('store_id'=>$v['sto_id']))->find();
                $res_store_user = M('store')->where(array('store_id'=>$res_user['s_id']))->find();
                $res_region_goods = M('region')->where(array('region_id'=>$res_store_goods['region_id']))->find();
                $res_region_user = M('region')->where(array('region_id'=>$res_store_user['region_id']))->find();
                if($res_region_user['region_id'] == $res_region_goods['region_id'] || $res_region_user['parent_id'] == $res_region_goods['region_id'] || $res_region_user['region_id'] == $res_region_goods['parent_id']){
                    //显示优惠价
                    $goods_list[$k]['first_price'] = ($v['first_discount_price'] < $v['first_cost_price']) && $v['first_discount_price'] ? $v['first_discount_price'] : $v['first_cost_price'];
//                    $goods_list[$k]['end_price'] = ($v['end_discount_price'] < $v['end_cost_price']) && $v['end_discount_price'] ? $v['end_discount_price'] : $v['end_cost_price'];
                    $goods_list[$k]['end_price'] = $goods_list[$k]['first_price'];
                }else{
                    //显示普通价
                    $goods_list[$k]['first_price'] = $v['first_cost_price'];
//                    $goods_list[$k]['end_price'] = $v['end_cost_price'];
                    $goods_list[$k]['end_price'] = $goods_list[$k]['first_price'];
                    $goods_list[$k]['ico'] = '';
                }
            }else if(strlen($v['sto_id']) && $v['sto_id'] == '0'){
                //显示优惠价
                $goods_list[$k]['first_price'] = ($v['first_discount_price'] < $v['first_cost_price']) && $v['first_discount_price'] ? $v['first_discount_price'] : $v['first_cost_price'];
//                $goods_list[$k]['end_price'] = ($v['end_discount_price'] < $v['end_cost_price']) && $v['end_discount_price'] ? $v['end_discount_price'] : $v['end_cost_price'];
                $goods_list[$k]['end_price'] = $goods_list[$k]['first_price'];
            }else{
                //显示普通价
                $goods_list[$k]['first_price'] = $v['first_cost_price'];
//                $goods_list[$k]['end_price'] = $v['end_cost_price'];
                $goods_list[$k]['end_price'] = $goods_list[$k]['first_price'];
                $goods_list[$k]['ico'] = '';
            }
        }

        //总筛选
        $res_sort = M('goods')
            ->table('ecm_goods g,ecm_store s,ecm_goods_spec gsp,ecm_storestock as ss')
            ->field('g.cate_name,substring_index(g.cate_name," ",1) as parent_name,count(substring_index(g.cate_name," ",1)) as num,group_concat(gsp.stock) as stocks,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist,g.sex,g.brand,gsp.spec_1value,gsp.spec_2,g.material,ss.stock_name')
            ->where('g.store_id = s.store_id AND g.goods_id = gsp.goods_id AND gsp.spec_3value = ss.storestock_id'.$conditions)
            ->group('g.goods_id')
            ->order('count(substring_index(g.cate_name," ",1)) desc')
            ->having('is_exist = "true"')
            ->select();
        if($_POST['cate_name']){
            $res_cate = M('gcategory')->where(array('cate_name'=>$_POST['cate_name']))->find();
            $temp_cate_pic = 'data/files/mall/gcategory/wish_'.$res_cate['cate_id'].'.png';

        }else{
            $temp_cate_pic = 'data/files/mall/gcategory/wish_0.png';

        }
        if($_POST['user_id']){
            $cond_collect['user_id'] = $_POST['user_id'];
            $res_collect = M('collect')->where($cond_collect)->field('item_id as goods_id ,user_id')->select();
            foreach ($goods_list as $key => $value){
                $res_spec = M('goods_spec')->group('spec_1value')->where(array('goods_id'=>$value['goods_id']))->field('spec_1')->select();
                $data = array_column($res_spec,'spec_1');
                $goods_list[$key]['spec'] = $data;
                if($res_collect){
                    if(in_array($goods_list[$key]['goods_id'],array_column($res_collect,'goods_id'))){
                        $goods_list[$key]['collect'] = true;
                    }else{
                        $goods_list[$key]['collect'] = false;
                    }
//                    if($goods_list[$key]['goods_id'] == 21){
//                        var_dump($goods_list[$key]['collect']);exit;
//                    }
                }else{
                    $goods_list[$key]['collect'] = false;
                }
            }
        }else{
            foreach ($goods_list as $key => $value){
                $res_spec = M('goods_spec')->group('spec_1value')->where(array('goods_id'=>$value['goods_id']))->field('spec_1')->select();
                $data = array_column($res_spec,'spec_1');
                $goods_list[$key]['spec'] = $data;
            }
        }
        //取所有一级分类
//        $array_unset = $this->array_unset_second($res_sort,'parent_name');
//        $arr = array_column($array_unset,'parent_name');
        $array_unset = M('gcategory')->where(array('parent_id'=>0))->select();
        $arr = array_column($array_unset,'cate_name');
        $data = array(
            'goods_list' => $goods_list,
            'cate' => $arr ? $arr : array(),
            'wish_url' => $res_pic['wish_url'],
            'cate_pic' => $temp_cate_pic ? $temp_cate_pic : '',
            'wish_none_url' => ''
        );
        render('10000', 'OK', $data);
    }

    //开屏广告
    function get_advertisement(){
        $res = M('advertisement_setting')->field('ecm_advertisement_setting.*,ecm_theme_setting.theme_title')->join('left join ecm_theme_setting on ecm_advertisement_setting.theme_id = ecm_theme_setting.theme_id')->where(array('ecm_advertisement_setting.type_id'=>1))->find();
        $res['advertisement_link'] = $res['advertisement_link'] ?  C('SITE_URL').$res['advertisement_link'] : '';
        $res['advertisement_url'] = C('SITE_URL').$res['advertisement_url'];
        $res['theme_title'] = $res['advertisement_title'];
        if($res['type'] == 1){
            $data['advertisement'] = $res;
            render('10000', 'OK', $data);
        }else if($res['type'] == 2){
            render('10004', '参数错误');
        }
    }

    //慈善
    function get_charitable(){
        $res = M('advertisement_setting')->where(array('type_id'=>2))->find();
        $res['advertisement_link'] = $res['advertisement_link'] ?  C('SITE_URL').$res['advertisement_link'] : '';
        $res['advertisement_url'] = C('SITE_URL').$res['advertisement_url'];
        $data = array(
          'advertisement' => $res
        );
        render('10000', 'OK', $data);
    }

    function array_unset_second($arr,$key){
        $tmp_arr = array();
        foreach($arr as $k => $v)
        {
            if(in_array($v[$key], $tmp_arr) || !$v[$key])   //搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
            {
                unset($arr[$k]); //销毁一个变量  如果$tmp_arr中已存在相同的值就删除该值
            }
            else {
                $tmp_arr[$k] = $v[$key];  //将不同的值放在该数组中保存
            }
        }
        //ksort($arr); //ksort函数对数组进行排序(保留原键值key)  sort为不保留key值
        return $arr;
    }

    function array_number_second($arr){
        $tmp_arr = array();
        foreach($arr as $k => $v)
        {
            if(is_numeric($v)){
                $tmp_arr[] = $v;
            }
        }

        return $tmp_arr;
    }

    function array_unset_number_second($arr){
        $tmp_arr = array();
        foreach($arr as $k => $v)
        {
            if(!is_numeric($v)){
                $tmp_arr[] = $v;
            }
        }

        return $tmp_arr;
    }

    function array_sort_second($arr1,$arr2){
        $c = array();
        for ($i = 0; $i < count($arr1); $i++) {
            for ($j = 0; $j < count($arr2); $j++) {
                if ($arr2[$j] == $arr1[$i]) {
                    $c[$i] = $arr2[$j];
                }
            }
        }
        return array_values($c);
    }

    function array_unset_sort_second($arr1,$arr2){
        $c = $arr2;
        for ($i = 0; $i < count($arr1); $i++) {
            for ($j = 0; $j < count($arr2); $j++) {
                if ($arr2[$j] == $arr1[$i]) {
                    unset($c[$j]);
                }
            }
        }
        return array_values($c);
    }

     function get_list_test(){
         $conditions = ' AND g.if_show=1 AND g.closed=0 AND s.state=1';
         $keyword = I('request.keyword', '');
         $kw = explode(' ',$keyword);
         $kw = array_filter($kw);
         sort($kw);
         if ($keyword) {
             //redis
             set_redis('hot_keyword',$keyword);
             foreach ($kw as $key => $value){
                 //先查男女
                 if($key == 0 && $key == count($kw) - 1){
                     $conditions .= ' AND (goods_name LIKE "%'.$value.'%" OR brand LIKE "%'.$value.'%" OR cate_name LIKE "%'.$value.'%" OR sex LIKE "%'.$value.'%" OR gsp.spec_1value LIKE "%'.$value.'%" OR gsp.spec_1 LIKE "%'.$value.'%" OR gsp.spec_3 LIKE "%'.$value.'%")';
                 }else if($key == 0){
                     $conditions .= ' AND (goods_name LIKE "%'.$value.'%" OR brand LIKE "%'.$value.'%" OR cate_name LIKE "%'.$value.'%" OR sex LIKE "%'.$value.'%" OR gsp.spec_1value LIKE "%'.$value.'%" OR gsp.spec_1 LIKE "%'.$value.'%" OR gsp.spec_3 LIKE "%'.$value.'%"';
                 }else if($key == count($kw) - 1){
                     $conditions .= ' OR goods_name LIKE "%'.$value.'%" OR brand LIKE "%'.$value.'%" OR cate_name LIKE "%'.$value.'%" OR sex LIKE "%'.$value.'%" OR gsp.spec_1value LIKE "%'.$value.'%" OR gsp.spec_1 LIKE "%'.$value.'%" OR gsp.spec_3 LIKE "%'.$value.'%")';
                 }else{
                     $conditions .= ' OR goods_name LIKE "%'.$value.'%" OR brand LIKE "%'.$value.'%" OR cate_name LIKE "%'.$value.'%" OR sex LIKE "%'.$value.'%" OR gsp.spec_1value LIKE "%'.$value.'%" OR gsp.spec_1 LIKE "%'.$value.'%" OR gsp.spec_3 LIKE "%'.$value.'%"';
                 }
             }
         }
         $brand = htmlspecialchars_decode(I('request.brand', ''));
         if ($brand) {
             $conditions .= ' AND brand LIKE "%'.$brand.'%"';
             //redis
             set_redis('hot_brand',$brand);
             //zRevRangeByScore 分数排行
             //var_dump($redis ->zRevRangeByScore('hot_theme','+inf','-inf'));
             //
         }

         $cate_id = I('request.cate_id', '0', 'intval');
         if ($cate_id) {
//            $conditions .= ' AND (cate_id_1=' . $cate_id . ' OR cate_id_2=' . $cate_id . ' OR cate_id_3=' . $cate_id . ' OR cate_id_4=' . $cate_id.')';

             //todo 调取分类查询
             $result = $this->get_cateList($cate_id);
             if($result['parent_id'] == 9999){
                 $conditions .= ' AND cate_id IN ('.$result['ids'].')';
             }else{
                 $conditions .= ' AND cate_id='.$result['ids'];
             }
         }
         $cate = I('request.cate', '');
         if ($cate) {
             $conditions .= ' AND cate_name LIKE "%'.$cate.'%"';
         }

         //排序
         $sort = I('request.sort', '');
         $order = I('request.order', '');
         if (!in_array($sort, array('sales', 'price', 'add_time', 'comments'))) {
             $sort = 'sales';
         }
         if (!in_array($order, array('desc', 'asc'))) {
             $order = 'desc';
         }
         //goods_id
         $goods_id = I('request.goods_id', '');
         if(trim($goods_id)){
             $conditions .= ' AND g.goods_id IN ('.$goods_id.')';
         }

         $goods_mod = M('goods');
         //新版本 不要已售罄商品

//        $goods_list = M('goods')
//            ->table('ecm_goods g,ecm_goods_spec gsp,ecm_storestock ss,ecm_store s,ecm_goods_statistics gs')
//            ->field('g.brand,g.goods_id,g.store_id,g.goods_name,g.default_image,g.price,g.market_price,gs.sales,gs.comments,g.add_time,gs.goods_id,group_concat(gsp.stock) as stocks,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 as is_exist')
//            ->where('g.goods_id = gsp.goods_id and gsp.spec_3value = ss.storestock_id and s.store_id = g.store_id and gs.goods_id = g.goods_id'.$conditions)
//            ->page(I('request.page', 1, 'intval') . ',10')
//            ->group('g.goods_id')
//            ->order($sort . ' ' . $order.',mall_sort_order asc')
//            ->select();

         $list = M('goods')
             ->table('ecm_goods g,ecm_goods_spec gsp,ecm_storestock ss,ecm_store s,ecm_goods_statistics gs')
             ->field('g.brand,g.goods_id,g.store_id,g.goods_name,g.default_image,g.price,g.market_price,gs.comments,g.add_time,group_concat(gsp.stock) as stocks,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist, MAX(case when gsp.stock=0 or gsp.price=0.00 or gsp.discount_price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.discount_price end) as end_discount_price, MIN(case when gsp.stock=0 or gsp.price=0.00 or gsp.discount_price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.discount_price end) as first_discount_price,MAX(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.price end) as end_cost_price,MIN(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then null else gsp.price end) as first_cost_price')
             ->where('g.goods_id = gsp.goods_id and gsp.spec_3value = ss.storestock_id and s.store_id = g.store_id and gs.goods_id = g.goods_id   '.$conditions)
             ->page(I('request.page', 1, 'intval') . ',10')
             ->group('g.goods_id')
             ->having('is_exist = "true"')
             ->order('is_exist desc,'.$sort . ' ' . $order.',mall_sort_order asc')
             ->buildSql();
         $goods_list = M('discount')->alias('d')
             ->field("cc.store_id as sto_id,ifnull(cc.ico ,'') as ico,gl.*")
             ->join('right join '.$list.' gl on d.goods_id = gl.goods_id')
             ->join('left join ecm_coupon_codes cc on d.coupon_codes_id = cc.id and cc.enabled = 1')
             ->group('gl.goods_id')
             ->select();
         if($_POST['token']){
             $res_token = M('app_token')->where(array('token'=>$_POST['token']))->find();
             $res_user = M('member')->where(array('user_id'=>$res_token['user_id']))->find();
         }
         foreach ($goods_list as $k => $v) {
             if ($v['sto_id'] && $_POST['token'] && $res_user){
                 $res_store_goods = M('store')->where(array('store_id'=>$v['sto_id']))->find();
                 $res_store_user = M('store')->where(array('store_id'=>$res_user['s_id']))->find();
                 $res_region_goods = M('region')->where(array('region_id'=>$res_store_goods['region_id']))->find();
                 $res_region_user = M('region')->where(array('region_id'=>$res_store_user['region_id']))->find();
                 if($res_region_user['region_id'] == $res_region_goods['region_id'] || $res_region_user['parent_id'] == $res_region_goods['region_id'] || $res_region_user['region_id'] == $res_region_goods['parent_id']){
                     //显示优惠价
                     $goods_list[$k]['first_price'] = ($v['first_discount_price'] < $v['first_cost_price']) && $v['first_discount_price'] ? $v['first_discount_price'] : $v['first_cost_price'];
                     $goods_list[$k]['end_price'] = ($v['end_discount_price'] < $v['end_cost_price']) && $v['end_discount_price'] ? $v['end_discount_price'] : $v['end_cost_price'];
                 }else{
                     //显示普通价
                     $goods_list[$k]['first_price'] = $v['first_cost_price'];
                     $goods_list[$k]['end_price'] = $v['end_cost_price'];
                     $goods_list[$k]['ico'] = '';
                 }
             }else if(strlen($v['sto_id']) && $v['sto_id'] == '0'){
                 //显示优惠价
                 $goods_list[$k]['first_price'] = ($v['first_discount_price'] < $v['first_cost_price']) && $v['first_discount_price'] ? $v['first_discount_price'] : $v['first_cost_price'];
                 $goods_list[$k]['end_price'] = ($v['end_discount_price'] < $v['end_cost_price']) && $v['end_discount_price'] ? $v['end_discount_price'] : $v['end_cost_price'];
             }else{
                 //显示普通价
                 $goods_list[$k]['first_price'] = $v['first_cost_price'];
                 $goods_list[$k]['end_price'] = $v['end_cost_price'];
                 $goods_list[$k]['ico'] = '';
             }
         }

         //热门分类
         $res_sort = M('goods')
             ->table('ecm_goods g,ecm_store s,ecm_goods_spec gsp,ecm_storestock as ss')
             ->field('g.cate_name,substring_index(g.cate_name," ",1) as parent_name,count(substring_index(g.cate_name," ",1)) as num,group_concat(gsp.stock) as stocks,group_concat(gsp.price) as prices,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style != 3 and gsp.price >4582.00) then 0 else 1 end) as sales,case when locate(1,group_concat(case when gsp.stock=0 or gsp.price=0.00 or (ss.stock_style!=3  and gsp.price >4582.00) then 0 else 1 end)) > 0 then "true" else "false" end as is_exist')
             ->where('g.store_id = s.store_id AND g.goods_id = gsp.goods_id AND gsp.spec_3value = ss.storestock_id'.$conditions)
             ->group('substring_index(g.cate_name," ",1)')
             ->order('count(substring_index(g.cate_name," ",1)) desc')
             ->having('is_exist = "true"')
             ->select();
         $data_sort = array_column($res_sort,'parent_name');
         //排序
         //关闭exist
//        if (!in_array( I('request.sort'), array('sales', 'price', 'add_time', 'comments')) && !in_array(I('request.order'), array('desc', 'asc'))) {
//            $last_names = array_column($goods_list,'is_exist');
//            array_multisort($last_names,SORT_DESC,$goods_list);
//        }
//        $_POST['user_id'] = 3;
         if($_POST['user_id']){
             $cond_collect['user_id'] = $_POST['user_id'];
             $res_collect = M('collect')->where($cond_collect)->field('item_id as goods_id ,user_id')->select();
             foreach ($goods_list as $key => $value){
                 $res_spec = M('goods_spec')->group('spec_1value')->where(array('goods_id'=>$value['goods_id']))->field('spec_1')->select();
                 $data = array_column($res_spec,'spec_1');
                 $goods_list[$key]['spec'] = $data;
                 if($res_collect){
                     if(in_array($goods_list[$key]['goods_id'],array_column($res_collect,'goods_id'))){
                         $goods_list[$key]['collect'] = true;
                     }else{
                         $goods_list[$key]['collect'] = false;
                     }
//                    if($goods_list[$key]['goods_id'] == 21){
//                        var_dump($goods_list[$key]['collect']);exit;
//                    }
                 }else{
                     $goods_list[$key]['collect'] = false;
                 }
             }
         }else{
             foreach ($goods_list as $key => $value){
                 $res_spec = M('goods_spec')->group('spec_1value')->where(array('goods_id'=>$value['goods_id']))->field('spec_1')->select();
                 $data = array_column($res_spec,'spec_1');
                 $goods_list[$key]['spec'] = $data;
             }
         }
         /*
         if ($goods_list) {
             foreach ($goods_list as $key => $goods) {
                 $goods_list[$key]['price'] = D('Promotion')->get_promotion_price($goods['goods_id'], $goods['spec_id']);
             }
         }
          */
         if(!$goods_list){
             $goods_list = array();
         }
         $res = M('banner_setting')->where(array('type_id'=>2))->select();
         $data = array(
             'goods_list' => $goods_list,
             'banner' => $res,
             'cate' => $data_sort ? $data_sort : array()
         );
         render('10000', 'OK', $data);

     }
    function get_test(){
        $cond['ecm_goods.closed'] = 0;
//        $conds['ecm_goods_spec.price'] <= 0;
//        $conds['ecm_goods_spec.stock'] <= 0;
//        $condss['ecm_goods_spec.spec_3value'] = 26;
//        $condss['ecm_goods_spec.price'] = array('egt',5000);
//        $condss['_logic'] = 'and';
//        $conds['_complex'] = $condss;
//        $conds['_logic'] = 'or';
        $conds = 'ecm_goods_spec.price = 0.00 or ecm_goods_spec.stock < 0 or (ecm_goods_spec.spec_3value = 26 and ecm_goods_spec.price > 4582)';
        $data = array();
        $res = M('goods')->field('ecm_goods_spec.*')->join('left join ecm_goods_spec on ecm_goods.goods_id = ecm_goods_spec.goods_id')->where($conds)->select();
        foreach ($res as $k => $v){
            $data[] = $v['spec_id'];
        }
        $dataa = array();
        $cond['ecm_goods.goods_id'] = array('NOT IN',$data);
        $ress = M('goods')->field('ecm_goods_spec.*')->join('left join ecm_goods_spec on ecm_goods.goods_id = ecm_goods_spec.goods_id')->where($cond)->select();
        foreach ($ress as $k => $v){
            if(!$v['goods_id'] or !$v['spec_id'] or !$v['spec_3value']){
                continue;
            }
            $dataa[] = array(
                'coupon_codes_id' => 2,
                'goods_id' => $v['goods_id'],
                'spec_id' => $v['spec_id'],
                'storestock_id' => $v['spec_3value']
            );
        }
        $resc = M('discount')->addAll($dataa);
        var_dump($dataa);exit;

    }

    function qrcode_test(){
        vendor('phpqrcode.phpqrcode');
        $user_id = 3;
        $url1 = C('SITE_URL').'data/files/qrcode/background.png';
        $url = C('SITE_URL').'mobile/index.php?app=qrcode&act=download&invite_code='.set_encrypt($user_id);

        $folder = dirname(dirname(dirname(dirname(__DIR__)))).'/data/files/users/user0'.$user_id;
        mkdirs($folder);
        $path = $folder.'/qrcode_'.$user_id.'.png';
        $this->set_qrcode($url,$path);
        $url2 = $path;
        $rs = mergeImage($url1,$url2,$folder.'/new_qrcode_'.$user_id.'.png');

    }

    function set_qrcode($url,$path){
//        $folder =  dirname(dirname(__DIR__)).'/Runtime/Logs/qrcode.png';
        vendor('phpqrcode.phpqrcode');
        $QRcode = new \Qrcode();
        $value = $url;
        $errorCorrectionLevel = "L";
        $matrixPointSize = "2.64";
        $rs = $QRcode::png($value, $path, $errorCorrectionLevel, $matrixPointSize,0, TRUE);
    }


}
